如果对象被释放,Objective-C 的弱属性应该指向 nil,但在这种情况下,弱属性似乎保留了对象。考虑以下情况:
@interface SillyObject : NSObject
@property (nonatomic, assign) NSInteger val;
-(void)printVal;
@end
@implementation SillyObject
-(void)printVal
{
NSLog(@"%d", self.val);
}
@end
-(void)saveReference
{
SillyObject* s = [SillyObject new];
s.val = 100;
[[ObjectCache sharedInstance] addWeakRef:s callback:^(NSString* junk) {
[s printVal];
}];
}
callSillyObjectBlocks 循环所有添加到缓存中的对象并调用相应的块(见下文)
-(void)callDeadObject
{
[self saveReference];
[[ObjectCache sharedInstance] callSillyObjectBlocks];
}
现在 saveReference 退出并且 SillyObject 应该被释放,但它没有并且弱引用不是 nil。
缓存的相关实现细节:
typedef void (^Callback)(NSString* junk);
@interface CacheSlot : NSObject
@property (nonatomic, copy) Callback callback;
@property (nonatomic, weak) id source;
// More irrelevant properties.
-(instancetype)initWithRef:(__weak id)obj callback:(Callback)cb;
@end
@implementation CacheSlot
@synthesize callback, source;
-(instancetype)initWithRef:(__weak id)obj callback:(Callback)cb
{
self = [super init];
if(self)
{
self.callback = cb;
self.source = obj;
}
return self;
}
@end
@interface ObjectCache()
// This array contains CacheSlot objects
@property (nonatomic, strong) NSMutableArray* savedObjects;
@end
// Implementation.
-(void)addWeakRef:(id)obj callback:(Callback)block
{
__weak id src = obj;
[self.savedObjects addObject:[[CacheSlot alloc] initWithRef:src callback:block]];
}
-(void)callSillyObjectBlocks
{
for(CacheSlot* slot in self.savedObjects)
{
if(slot.source)
{
slot.callback(@"Whatever!");
}
else
{
// Remove the slot from cache
}
}
}
最初调用 saveReference 应该创建一个临时对象,该对象在函数退出后立即被释放(如果我调用 addWeakRef:nil 则它会这样做)。
调用 saveReference 后,我运行 callSillyObjectBlocks 并且不应调用添加的对象的相应块,但会使用对象的值调用它。输出:
100