Playing around with ARC: Force release irritation?

佐手、 提交于 2019-12-07 17:11:57

问题


I am currently playing around with ARC a bit to get some things figured out, before starting to do the actual work. I did setup this code:

NSNumber* n = [[NSNumber alloc] initWithInt:3];
__weak NSNumber* weakN = n;
n = nil;
NSLog(@">>>: %@ %@", n, weakN);

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?

Another thing is, that I am pretty sure, the below code was giving me a hard time when starting with arc:

__weak NSNumber* weakN2 = [[NSNumber alloc] initWithInt:3];
NSLog(@">>>: %@", weakN2);

I am pretty sure, I've had some problems with similar code, as arc would release the object straight after initialization, as there is no strong reference to the object. Unfortunately, the output of the above is ">>>: 3".

It would be great to get some clarification on this stuff. I am clearly missing something here!

Best regards, Michael


回答1:


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.




回答2:


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";)




回答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.



来源:https://stackoverflow.com/questions/10669448/playing-around-with-arc-force-release-irritation

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