Playing around with ARC: Force release irritation?

点点圈 提交于 2019-12-05 21:27:28

In addition to what kevboh said, it's also rather pointless to create weak references to simple immutable Foundation objects like NSNumber. For performance reasons, Foundation might well vend you a cached object instead of creating an entirely new one. And if it doesn't now, then it might in some future release.

The upshot is that you're probably not the sole owner of the object returned by [[NSNumber alloc] initWithInt:3], no matter what you think.

Well, you just picked a bad object to test this with. If you do it with NSString's (or most other objects), you get the expected result:

NSString* n = [[NSString alloc] initWithFormat:@"3"];
__weak NSString* weakN = n;
n = nil;
NSLog(@">>>: %@ %@", n, weakN);
// Output is (null) (null)

__weak NSString* weakN2 = [[NSString alloc] initWithFormat:@"3"];
NSLog(@">>>: %@", weakN2);
// Output is (null)

The behavior of NSNumber is caused because the class is caching the number that was created so is actually still valid. The same behavior will be exhibited if you use string constants that are compiled in as part of the code. (Like NSString* n = @"3";)

I expected n and weakN to be nil, as n = nil; should trigger a release in my eyes? Unfortunately it doesn't. The output is ">>>: (null) 3". What am I missing here?

ARC doesn't work like that. Ownership of the object is nondeterministic; ARC likely held on to it until the end of your function. You should not expect deallocs to happen and instead use strong/weak references when you intend ownership to happen.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!