1

如果对象被释放,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
4

1 回答 1

3

每当您有一个从块外部引用变量的块时,您也需要将其声明为。否则你会得到一个强有力的参考。所以应该是:

-(void)saveReference
{
  SillyObject* s = [SillyObject new];
  s.val = 100;
  SillyObject * __weak weakSilly = s;

  [[ObjectCache sharedInstance] addWeakRef:s callback:^(NSString* junk) {
    [weakSilly printVal];
  }];
}

同时,您可以通过__weak从其他几个位置删除来简化代码,因为它们只会影响不会在相关时间保留实例的方法参数:

-(instancetype)initWithRef:(id)obj callback:(Callback)cb {
    ...
}

-(void)addWeakRef:(id)obj callback:(Callback)block
{
  [self.savedObjects addObject:[[CacheSlot alloc] initWithRef:obj callback:block]];
}
于 2013-10-04T13:05:43.977 回答