Why __weak object will be added to autorelease pool?

筅森魡賤 提交于 2019-12-07 14:39:21

问题


id __weak obj1 = obj0;

equals

id __weak obj1 = obj0;
id __autoreleasing tmp = obj0;

In Pro multithreading and memory management for iOS and OSX.

But why the obj1 need to add to the autorelease pool, I think making a weak pointer of an object should not affect its lifetime.


回答1:


{
    NSObject* sp = [NSObject new];
    NSObject* __weak wp = sp;
}

the above code is translate to:

id sp = objc_msgSend(NSObject, "new");
id wp;
objc_initWeak(&wp, sp);
objc_destroyWeak(&wp);
objc_storeStrong(&sp, 0);

1) obj_initWeak merely associate the weak pointer wp with the strong pointer sp to ensure that when the object pointed by sp is dealloced wp would auto reset to nil, which would not intecrement the retain count of the pointed object.
2)obj_destroyWeak destroy the association of the weak pointer and strong pointer.
3)obj_storeStrong in the last statement equal to [sp release].

But as soon as we use the weak pointer, the compiler would generate a new reference for the object pointed.

{
    NSObject* sp = [NSObject new];
    NSObject* __weak wp = sp;
    NSLog(@"%@", wp);
}

becomes

id sp = objc_msgSend(NSObject, "new");
id wp;
objc_initWeak(&wp, sp);
id tmp = objc_loadWeakRetained(wp);
NSLog(@"%@", wp);
objc_release(tmp);
objc_destroyWeak(&wp);
objc_storeStrong(&sp, 0);

objc_loadWeakRetained would increment the reference count to ensure that tmp is alive in the NSLog statement. objc_release reset the object to the original state.

In conclusion, this design of __weak ensure that during the usage of weak pointer, its state is consistent. The new implmenetation of __weak of Apple LLVM version 8.0.0 (clang-800.0.42.1) do not postpond the release to autoreleasepool, but use objc_release directly.



来源:https://stackoverflow.com/questions/40993809/why-weak-object-will-be-added-to-autorelease-pool

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