Objective-C 的这两种不同系列之间有什么区别?为什么一种可以工作,另一种却不行?
如果我尝试在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
seedsArray = ...
分配给seedsArray
字段。self.seedsArray = ...
调用setSeedsArray:
,它是seedsArray
属性 的 setter。如果您
@synthesize seedsArray
,这两种形式的行为几乎相同(请参阅下面@JeremyP的评论),但如果您定义自己的setter,则只有第二种形式会设置属性并调用您的代码。seedsArray = ...
assigns to theseedsArray
field.self.seedsArray = ...
invokessetSeedsArray:
, which is the setter for theseedsArray
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.