简体   繁体   English

为什么保留财产可能无法保留在Objective-C上?

[英]Why retain property may not retain on Objective-C?

Why the following code crashes? 为什么以下代码崩溃? Commented code doesn't crash. 注释的代码不会崩溃。

@property (retain) NSDate *lastCurrentDate;

...

@synthesize lastCurrentDate;

- (void)viewWillAppear:(BOOL)animated {
    BOOL crash = [lastCurrentDate isEqualToDate:[NSDate date]]);
}

- (void)viewDidDisappear:(BOOL)animated {
    //lastCurrentDate = [[NSDate date] retain];
    lastCurrentDate = [NSDate date];
}

So, why retain property may not retain on Objective-C? 那么,为什么保留财产可能无法保留在Objective-C上呢?

When you write @synthesize lastCurrentDate - you also create variable named ' lastCurrentState ', and when you write lastCurrentDate = [NSDate date]; 当您编写@synthesize lastCurrentDate ,您还将创建名为“ lastCurrentState ”的变量,并且当您编写lastCurrentDate = [NSDate date]; you directly access this variable. 您可以直接访问此变量。 Properties should be accessed via dot: self.lastCurrentDate = ....; 应该通过点访问属性: self.lastCurrentDate = ....;

In last xCodes you don't need to write synthesize - it do it automatically, but creates variable named with '_' prefix. 在最后的xCodes中,您无需编写synthesize-它会自动执行,但是会创建以'_'前缀命名的变量。 It equals to: @synthesize variable = _variable; 它等于: @synthesize variable = _variable;

Use self.lastCurrentDate = [NSDate date] . 使用self.lastCurrentDate = [NSDate date] Because when you use self.lastCurrentDate , it will assign via setter method. 因为当您使用self.lastCurrentDate ,它将通过setter方法进行分配。 You declare vaiable via retain property, So your setter method will do two operation, assign and retain . 您可以通过keep属性声明vaiable,因此您的setter方法将执行两项操作,即assignretain

因为您直接分配给实例变量,所以没有使用属性访问器方法:

self.lastCurrentDate = [NSDate date];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM