【问题标题】:Question about how objective c property setters work关于客观 c 属性设置器如何工作的问题
【发布时间】:2011-02-21 20:33:20
【问题描述】:

我对属性的两个假设是否正确?

@interface Foo : NSObject {
NSDate *Created;
}

@property (nonatomic, retain) NSDate *Created;

@end

@implementation Foo

@synthesize Created;

- (id) init {
if(self = [super init])
{
    Created = [NSDate date]; //this will not call the setter and instead just access the variable directly, which means it will not automatically get retained for me.
    self.Created = [NSDate date]; // this will call the setter, which will retain the variable automatically for me.
}
return self;
}

- (void)dealloc {
    [Created release]   
    [super dealloc];
}
@end

【问题讨论】:

    标签: iphone objective-c properties


    【解决方案1】:

    是的;没错。

    注意实例变量应该是created;它应该以小写字母开头。我也推荐creationDate

    【讨论】:

      【解决方案2】:

      建议不要在dealloc或init中使用属性,所以在init方法中而不是self.propertyName = [NSDate date];你应该做fieldName = [[NSDate alloc] init];dealloc中的释放很好

      More about it

      【讨论】:

      • 我不买“不要在 init 中使用属性”的东西。我专门使用“保留”属性,所以我不必密切关注保留/释放。每当我尝试通过使用原始 ivar 引用来“优化”时,我总是会遇到一个保留/释放错误。我不使用自定义的setter/getter,只使用默认的@synthesize,它非常适合在init 中使用。
      • 当您使用 ivar 引用的唯一地方是 init 和 dealloc 时,搞砸并不是那么容易。我不使用它进行优化,而仅仅是因为这是苹果推荐的。
      猜你喜欢
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2016-10-05
      • 2010-12-10
      相关资源
      最近更新 更多