__weak link is still a mystery to me

NSString *myString = [NSString stringWithFormat:@"string1"]; __weak NSString *myString1 = myString; myString= nil; NSLog(@"%@, %@",myString,myString1); 

I was expecting null , null . But the output is string1, (null) . Why is myString1 still storing the value since myString is nil?

+4
source share
4 answers

Weak links only get nullified when the object is freed. This object is not immediately freed (this is probably in the autorun pool here, although there are many other reasons why something can be held in different situations), so the link remains alive.

+8
source

Try something like this:

 NSString *myString; NSString* __weak myString1; @autoreleasepool{ myString= [NSString stringWithFormat:@"string1"]; myString1= myString; myString= nil; } NSLog(@"%@, %@",myString,myString1); 

Explanation

You have probably noticed that there are many ways to select a line or an object in general:

1) [NSString stringWithFormat: ...] / [[NSString alloc] initWithFormat: ...];
2) [NSArray arrayWithArray: ...] / [[NSArray alloc] initWithArray: ...];
...

(Also for many other classes)

The first category of methods returns an object with automatic implementation. The second is not an auto-implemented object. Indeed, if in the above code you use alloc + initWithFormat: instead of stringWithFormat: you do not need an autostart pool to see that both objects are equal to zero.

+3
source

I think this quote from Memory Management Guide can answer your question.

In particular, you should not create classes so that dealloc is called when you think it will be called. A call to dealloc can be delayed or bypassed, either because of an error or because of an application crash.

+1
source

The output should be (null), string1 , not string1, (null) . You must have typed it incorrectly.

You explicitly set one link to nil, but another link is still used within the scope (because you use it in NSLog ). Therefore, it will not be released by ARC until this use is completed.


Weak link does not rest on it. The fact that you use it means that ARC will hold it (without adding a release code). After this use is completed, ARC will free the object, and then the weak link will be fixed.

0
source

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


All Articles