为什么__weak对象将被添加到自动释放池? [英] Why __weak object will be added to autorelease pool?
问题描述
id __weak obj1 = obj0;
等于
id __weak obj1 = obj0;
id __autoreleasing tmp = obj0;
在用于iOS和OSX的Pro多线程和内存管理中.
但是为什么obj1
需要添加到自动释放池中,我认为为对象创建弱指针不应影响其寿命.
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.
推荐答案
{
NSObject* sp = [NSObject new];
NSObject* __weak wp = sp;
}
以上代码被翻译为:
id sp = objc_msgSend(NSObject, "new");
id wp;
objc_initWeak(&wp, sp);
objc_destroyWeak(&wp);
objc_storeStrong(&sp, 0);
1)obj_initWeak
仅将弱指针wp
与强指针sp
关联,以确保当sp
所指的对象被解除分配时wp
会自动重置为nil,这不会使保留指向的对象的数量.
2)obj_destroyWeak
破坏弱指针和强指针的关联.
3)最后一个语句中的obj_storeStrong
等于[sp release]
.
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);
}
成为
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
将增加引用计数,以确保tmp
在NSLog
语句中仍然有效.
objc_release
将对象重置为原始状态.
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.
最后,__weak
的这种设计可确保在使用弱指针期间,其状态是一致的. Apple LLVM version 8.0.0 (clang-800.0.42.1)
的__weak
的新实现不会将发布推迟到autoreleasepool
,而是直接使用objc_release
.
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.
这篇关于为什么__weak对象将被添加到自动释放池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!