从弱强引用中可以理解的是:
然后我用这个例子(取自SO中的其他线程)尝试了我的完整代码:
- (void)viewDidLoad
{
[super viewDidLoad];
NSDate* date = [[NSDate alloc] init]; // date stays around because it's __strong
__weak NSDate* weakDate = date;
// Here, the dates will be the same, the second pointer (the object) will be the same
// and will remain retained, and the first pointer (the object reference) will be different
NSLog(@"Date(%p/%p): %@", &date, date, date);
NSLog(@"Weak Date(%p/%p): %@", &weakDate, weakDate, weakDate);
// This breaks the strong link to the created object and the compiler will now
// free the memory. This will also make the runtime zero-out the weak variable
date = nil;
NSLog(@"Date(%p/%p): %@", &date, date, date);
NSLog(@"Weak Date(%p/%p): %@", &weakDate, weakDate, weakDate);
}
我只是意识到这没有给出预期的结果:
Date(0xbfffdccc/0x713df20): 2013-12-04 04:19:30 +0000
Weak Date(0xbfffdcc8/0x713df20): 2013-12-04 04:19:30 +0000
Date(0xbfffdccc/0x0): (null)
Weak Date(0xbfffdcc8/0x713df20): 2013-12-04 04:19:30 +0000
为什么weakDate
的第二次打印仍然打印出来?我有错误的理解吗?
注意:
我在 iOS模拟器iOS 6.0
中测试的 Xcode 4.5.1 中使用 ARC