) { brea...">

Why the loop variable becomes "nil" after the loop

I have:

NSDictionary* server;

for (server in self.servers)
{
    if (<some criterium>)
    {
        break;
    }
}

// If the criterium was never true, I want to use the last item in the
// the array. But turns out that `server` is `nil`.

The cycle block never changes server.

servers- this is NSMutableArraywith dictionaries, a property that has not been changed during the cycle.

Why serverdoes it matter nilafter the end of the cycle?

I first used such a variable after a loop. Without thinking too much, I assumed this would work (in the old days of C):

int i;
for (i = 0; i < n; i++)
{
    ...
}
+4
source share
3 answers

, ​​ . , , .

. . , , . , , . (, ) .

, . , . , . .

+7

, for-loop, nil, ( , break, @rmaddy).

, :

for (NSDictionary* server in self.servers)
{
    //... server is not nil
}
//here server doesn't exist (out of scope)

self.servers var , :

NSDictionary* serverSave;

for (NSDictionary* server in self.servers)
{
    serverSave = server;
}
//here you can use serverSave, which will contain the last value of self.servers

, .

+5

, Objective-C ARC nills (. " " Objective C).

, :

NSDictionary* server; // server is nil here

for (server in self.servers)
{
    ... // Does not set server to nil.
}

server nil.

, :

NSDictionary *dict;

for (NSDictionary* server in self.servers)
{
    if (server == whatever you want){
        dict = server;
        break;
    }
}

:

NSDictionary *dict;

for (NSDictionary* server in self.servers)
{
    dict = server;
}
-1

Source: https://habr.com/ru/post/1648292/


All Articles