我遇到了一个奇怪的内存泄漏问题。以下的
然而,如果我去掉实例变量
这是什么原因呢?我认为
Car
类的对象永远不会被释放。然而,如果我去掉实例变量
_unsafe_self
并在init
方法内声明(和以前一样赋值)该变量,则泄漏消失了。这是什么原因呢?我认为
__weak
应该是弱引用,无论是实例变量还是其他任何东西。@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