gpt4 book ai didi

objective-c - 我还没有理解弱引用和强引用

转载 作者:搜寻专家 更新时间:2023-10-30 19:50:54 24 4
gpt4 key购买 nike

By books 首先解释了有关“无效”引用的问题(使用 ARC),如本例所示:

NSDate* date1=[[NSDate alloc]init];
NSDate* date2=date1;
[date1 release];
NSLog(@"%@",date2); // bad access

所以我理解了保留/释放机制:在这种情况下,指令是:

date2=[date1 retain];

但是当谈到强引用/弱引用时,我觉得这很矛盾:

“默认情况下,引用是强引用。如果您将对象分配给强引用,ARC 会假定您希望该对象保留并隐式保留它”

这不是和之前说的自相矛盾吗?
默认情况下 date2 是强的,因此它应该隐式保留 date1 并且不会出现错误的访问异常。
当然我误解了一些东西,有人可以向我解释一下吗?

最佳答案

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
}

关于objective-c - 我还没有理解弱引用和强引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10237303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com