注意:这个问题看起来很相似,但不是:When does an associated object get released?
我正在向UIView
实例添加第二个描述,如下所示:
- (void) setSecondDescription:(UIView*)view description2:(NSString*)description2 {
objc_setAssociatedObject (view,&key,description2,OBJC_ASSOCIATION_RETAIN);
}
- (NSString*) secondDescription:(UIView*)view {
return (id)objc_getAssociatedObject(view, &key);
}
如果UIView
deallocs,关联的描述2是否会被解除分配?有没有办法让这种情况自动发生?
答案 0 :(得分:64)
如果您想实际查看整个dealloc时间轴的描述,请参阅WWDC 2011,Session 322,36:22。但是,这是基本的纲要(我想记住它,所以这是我的代码中的实际注释)。
请注意,关联对象在生命周期结束时被释放。
// General Information
// We take advantage of the documented Deallocation Timeline (WWDC 2011, Session 322, 36:22).
// 1. -release to zero
// * Object is now deallocating and will die.
// * New __weak references are not allowed, and will get nil.
// * [self dealloc] is called
// 2. Subclass -dealloc
// * bottom-most subclass -dealloc is called
// * Non-ARC code manually releases iVars
// * Walk the super-class chain calling -dealloc
// 3. NSObject -dealloc
// * Simply calls the ObjC runtime object_dispose()
// 4. object_dispose()
// * Call destructors for C++ iVars
// * Call -release for ARC iVars
// * Erase associated references
// * Erase __weak references
// * Call free()
答案 1 :(得分:3)
是。取消分配对象时,将自动释放任何关联对象(使用RETAIN
或COPY
关联类型)。
答案 2 :(得分:3)
简而言之,是 - 当释放拥有对象时,将释放保留的关联对象。请参阅Apple的documentation
的第一部分答案 3 :(得分:0)
Jody Hagins的第4节answer说“擦除相关引用”,这并未明确暗示引用已被释放。所以我使用下面的一段代码(注意WITHOUT ARC)来测试它。
@interface AssociatedObjectHelper : NSObject
@end
@implementation AssociatedObjectHelper
- (void) dealloc
{
NSLog(@"In %s", __FUNCTION__);
[super dealloc];
}
@end
@implementation AppDelegate
...
- (void) testReleaseAssociatedObject
{
static const NSString *key = @"testKey123";
NSObject *ob = [NSObject new];
AssociatedObjectHelper *assocOb = [AssociatedObjectHelper new];
objc_setAssociatedObject(ob, key, assocOb, OBJC_ASSOCIATION_RETAIN);
[assocOb release];
[ob release];
}
调用上面的代码确实最终调用 - [AssociatedObjectHelper dealloc],带有以下堆栈跟踪:
#0 0x000000010000528f in -[AssociatedObjectHelper dealloc]
#1 0x00007fff8a0bb89c in objc_object::sidetable_release(bool) ()
#2 0x00007fff8a0a537f in _object_remove_assocations ()
#3 0x00007fff8a0a1644 in objc_destructInstance ()
#4 0x00007fff8a0a1595 in object_dispose ()
#5 0x00007fff8a0bb89c in objc_object::sidetable_release(bool) ()
#6 0x000000010000e9b6 in -[AppDelegate testReleaseAssociatedObject]
在Xcode 7.0.1上测试