Jody Hagins回答中的第 4 节说“擦除关联的引用”,这并没有明确暗示引用已被释放。所以我用下面的一段代码(注意没有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 上测试