Objective-C 的这两种不同系列之间有什么区别?为什么一种可以工作,另一种却不行?

发布于 2024-08-28 04:10:09 字数 974 浏览 4 评论 0原文

如果我尝试在 seedsArray = tempSeedsArray 之后释放 tempSeedsArray ,我会收到 EXEC_BAD_ACCESS,并且 Instruments 显示 tempSeedsArray 有已被释放两次。这是我的 viewWillAppear 方法:

- (void)viewWillAppear:(BOOL)animated {  
    NSString *arrayFilePath = [[NSBundle mainBundle] pathForResource:@"SeedsArray" ofType:@"plist"];  
    NSLog(@"HIT!");  
    NSMutableArray *tempSeedsArray = [[NSMutableArray alloc] initWithContentsOfFile:arrayFilePath];  
    seedsArray = tempSeedsArray;  
    NSLog(@"%u", [seedsArray retainCount]);  
    [seedsArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];  
    [super viewWillAppear:animated];  
}

seedsArray 是一个 NSMutableArray,设置为非原子属性和保留属性,并且是合成的。

但是,如果我将seedsArray = tempSeedsArray更改为self.seedsArray = tempSeedsArray(或[self seedsArray] = tempSeedsArray等),我可以释放tempSeedsArray。有人可以简单地向我解释一下这是为什么吗,因为我很困惑!

谢谢

If I try and release tempSeedsArray after seedsArray = tempSeedsArray , I get an EXEC_BAD_ACCESS, and Instruments shows that tempSeedsArray has been released twice. Here is my viewWillAppear method:

- (void)viewWillAppear:(BOOL)animated {  
    NSString *arrayFilePath = [[NSBundle mainBundle] pathForResource:@"SeedsArray" ofType:@"plist"];  
    NSLog(@"HIT!");  
    NSMutableArray *tempSeedsArray = [[NSMutableArray alloc] initWithContentsOfFile:arrayFilePath];  
    seedsArray = tempSeedsArray;  
    NSLog(@"%u", [seedsArray retainCount]);  
    [seedsArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];  
    [super viewWillAppear:animated];  
}

seedsArray is an NSMutableArray set as a nonatomic and a retain property, and is synthesised.

However, if I change seedsArray = tempSeedsArray to self.seedsArray = tempSeedsArray (or [self seedsArray] = tempSeedsArray etc.), I can release tempSeedsArray. Could someone please explain simply to me why this is, as I am very confused!

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画离情绘悲伤 2024-09-04 04:10:09
  1. seedsArray = ... 分配给 seedsArray 字段
  2. self.seedsArray = ... 调用 setSeedsArray:,它是 seedsArray 属性 的 setter。

如果您@synthesize seedsArray,这两种形式的行为几乎相同(请参阅下面@JeremyP的评论),但如果您定义自己的setter,则只有第二种形式会设置属性并调用您的代码。

  1. seedsArray = ... assigns to the seedsArray field.
  2. self.seedsArray = ... invokes setSeedsArray:, which is the setter for the seedsArray property.

If you @synthesize seedsArray, these two form will behave almost the same (see @JeremyP's comments below), but if you define your own setter, only the second form will set the property and invoke your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文