Strong 是默认设置,因为它通常是您想要的,但是使用 ARC,编译器会分析对象的生命周期需要多长时间并在适当的时间释放内存。例如:
- (void)someMethod
{
NSDate* date = [[NSDate alloc] init]; // date is __strong by default
NSLog(@"The date: %@", date); // date still contains the object created above
// Sometime before this point, the object date pointed to is released by the compiler
}
弱引用只保留对象,而它有一个或多个其他强引用。一旦最后一个强引用被破坏,编译器就会释放该对象,并且nil
运行时将弱对象引用(变量)更改为。这使得弱变量在局部范围内几乎没有用,就像上面的例子一样。例如:
- (void)someMethod
{
__weak NSDate* date = [[NSDate alloc] init]; // The date created is released before it's ever assigned to date
// because date is __weak and the newly created date has no
// other __strong references
NSLog(@"The date: %@", date); // This always prints (null) since date is __weak
}
看一个弱变量和强变量在局部范围内一起工作的例子(这只会严重限制有用性,这里实际上只是为了演示弱变量引用):
- (void)someMethod
{
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: %@", date); // prints (null) as expected
NSLog(@"Weak Date: %@", weakDate); // also prints (null) since it was weak and there were no more strong references to the original object
}