when will the retained object (that assigned to weak variable object) be released

血红的双手。 提交于 2019-12-13 06:11:51

问题


these code will get a warning: assigning retained object to weak variable object will be released after assignment

__weak NSString *str = [[NSString alloc] initWithFormat:@"1234"];
NSLog(@"url:%@",str);

but the nslog will print 1234 normally,seems that the object isn't released after assignment , so when will the release happend?


回答1:


You can get the behavior you expect by setting OBJC_DISABLE_TAGGED_POINTERS to YES in the program's environment. For example, you can set it in your scheme in Xcode like this:

What's going on (if you don't set that environment variable) is the Objective-C runtime supports tagged pointer strings. This means that short strings of common characters are encoded entirely in the 64-bit object reference, stored in the str variable. There is no heap allocation. Since there is no heap allocation for the string, and since the string cannot itself have references to other objects, the runtime knows it doesn't actually need to arrange for the __weak variable to be set to nil, so it doesn't.

By setting that environment variable, you disable the use of all tagged pointers, including tagged pointer strings. So I wouldn't recommend it for production code.

You can read more about tagged pointer strings in this excellent article by Mike Ash.



来源:https://stackoverflow.com/questions/41178840/when-will-the-retained-object-that-assigned-to-weak-variable-object-be-release

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