Objective c 为什么该代码在ARC下泄漏?(一个弱实例变量)

Objective c 为什么该代码在ARC下泄漏?(一个弱实例变量),objective-c,cocoa,Objective C,Cocoa,我正面临一个奇怪的漏洞。以下Car类的对象永远不会被释放 但是,如果我去掉实例变量\u safe\u self,而是在init方法中声明(并像以前一样分配)变量,泄漏就会消失 这可能是什么原因造成的?我认为无论是否是实例变量,\uu弱总是弱的 @interface Car : NSObject @end @implementation Car { id _obs; __weak Car *_unsafe_self; } - (id)init { if (!(self = [sup

我正面临一个奇怪的漏洞。以下
Car
类的对象永远不会被释放

但是,如果我去掉实例变量
\u safe\u self
,而是在
init
方法中声明(并像以前一样分配)变量,泄漏就会消失

这可能是什么原因造成的?我认为无论是否是实例变量,
\uu弱
总是弱的

@interface Car : NSObject
@end

@implementation Car {
  id _obs;
  __weak Car *_unsafe_self;
}

- (id)init {
  if (!(self = [super init]))
    return nil;

  _unsafe_self = self;

  _obs = [[NSNotificationCenter defaultCenter]
          addObserverForName:NSWindowDidMoveNotification
          object:nil
          queue:[NSOperationQueue mainQueue]
          usingBlock:^(NSNotification *note) {
              NSLog(@"hello %@", _unsafe_self);
            }];

  return self;
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:_obs];
}
@end

\u unsafe\u self
self->\u unsafe\u self
相同,因此

_obs = [[NSNotificationCenter defaultCenter]
          addObserverForName:NSWindowDidMoveNotification
          object:nil
          queue:[NSOperationQueue mainQueue]
          usingBlock:^(NSNotification *note) {
              NSLog(@"hello %@", _unsafe_self);
            }];
捕获
self
,导致阻止
self
解除分配的保留周期

这不会导致保留周期:

__weak Car *weakSelf = self;
_obs = [[NSNotificationCenter defaultCenter]
        addObserverForName:NSWindowDidMoveNotification
        object:nil
        queue:[NSOperationQueue mainQueue]
        usingBlock:^(NSNotification *note) {
            NSLog(@"hello %@", weakSelf);
        }];

使用property
self.unsafe\u self
将使这一点在代码中更为明显,但已经有足够多的“property vs ivar”Q&As:-)