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.

有帮助吗?

解决方案

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.

其他提示

Constant strings are a bad way to learn about ARC. Logging is a bad way to learn about ARC.

Constant strings are effectively singletons and will never be released.

Logging captures variables in ways you don't know about.

Debug builds don't nil out weak references immediately.

Essentially, you can't do little "tests" of ARC in standalone functions like this.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top