Search code examples
objective-cautomatic-ref-countingweak

__weak example in ARC code


I'm trying to understand how does __weak works in ARC code. Here is my example:

NSString *string = @"Hi!"; //1
__weak NSString *secondString = string; //2
string = @"Hello world!"; //3

NSLog(@"STR: %@", secondString); //4

I expect that NSLog shows me "nil", but it shows "Hi!". Why? This string must be dealloced at the third line.


Solution

  • Strings like that are static and will never be released. Try with manually allocated objects:

    #import <Foundation/Foundation.h>
    
    int main()
    {
        NSObject* strongPtr = [NSObject new];
        NSObject* __weak weakPtr = strongPtr;
        NSLog(@"weak=%@", weakPtr);
    
        strongPtr = nil;
        NSLog(@"weak=%@", weakPtr);
    }
    

    The output should be

    2014-01-16 15:07:49.376 a.out[34078:507] weak=<NSObject: 0x7fe391c08230>
    2014-01-16 15:07:49.379 a.out[34078:507] weak=(null)
    

    Another common reason why tests like this may appear to fail is autorelease pools — if any of APIs autorelease the object behind the scene, you may have to wait until the next hop of the event loop to see weak pointers becoming nil.