先说结论:
对象被释放的时候, 其dealloc方法执行之前, 它的所有weak属性都已经被设置为nil. 因此, 如果期望在dealloc里访问weak属性, 那是不行的.
项目最近遇到一个坑, 原因是对weak属性何时被设置为nil理解不够. 问题抽象如下:
@interface CheckBase : NSObject
- (void)printMessage;
@end
@class WeakInternalPlayerHolder;
@interface InternalPlayer : CheckBase
@property (strong, nonatomic) WeakInternalPlayerHolder *weakSelfHolder;
@end
@interface WeakInternalPlayerHolder : CheckBase
@property (weak, nonatomic) InternalPlayer *weakInterPlayer;
- (void) doSomeWork;
@end
@interface Player : CheckBase
@property (strong, nonatomic) InternalPlayer *interPlayer;
+ (void)doTest;
@end
@implementation CheckBase
-(void)dealloc {
NSLog(@"%@ dealloc", NSStringFromClass([self class]));
}
- (void)printMessage {
NSLog(@"message from %@", NSStringFromClass([self class]));
}
@end
@implementation InternalPlayer
- (instancetype)init
{
self = [super init];
if (self) {
_weakSelfHolder = [[WeakInternalPlayerHolder alloc] init];
_weakSelfHolder.weakInterPlayer = self;
}
return self;
}
-(void)dealloc {
NSLog(@"self:%@ weakself:%@", self, self.weakSelfHolder.weakInterPlayer);
[self.weakSelfHolder doSomeWork];
}
@end
@implementation WeakInternalPlayerHolder
- (void)doSomeWork {
[self.weakInterPlayer printMessage];
}
@end
@implementation Player
- (instancetype)init
{
self = [super init];
if (self) {
_interPlayer = [[InternalPlayer alloc] init];
}
return self;
}
- (void)dealloc
{
NSLog(@"internal obj:%@", self.interPlayer);
[self.interPlayer printMessage];
}
+ (void)doTest {
Player *p = [[Player alloc] init];
NSLog(@"weak internal player:%@", p.interPlayer.weakSelfHolder.weakInterPlayer);
p = nil;
NSLog(@"all release");
}
@end
简而言之, 上述问题对象关系是这样的:
Player---(强引用)--->InternalPlayer---(强引用)---->WeakInternalPlayerHolder---(弱引用)--->InternalPlayer.
我们期望在InternalPlayer的dealloc方法通过弱引用的指针, 让InternalPlayer打印一个消息.
然而, 运行[Player doTest]得到如下日志输出:
weak internal player:<InternalPlayer: 0x61800000eb20>
internal obj:<InternalPlayer: 0x61800000eb20>
message from InternalPlayer
Player dealloc
self:<InternalPlayer: 0x61800000eb20> weakself:(null)
InternalPlayer dealloc
WeakInternalPlayerHolder dealloc
all release
其中的语句[self.weakSelfHolder doSomeWork];
并没有得到预期的结果.
从其中的日志:self:<InternalPlayer: 0x61800000eb20> weakself:(null)
看出来弱引用对象在dealloc里已经是nil了.
这个问题从直觉上比较难接受: InternalPlayer对象分明还没有释放(日志打印self是正确的地址), 然而它的一个弱引用却已经是nil了.