Question about how objective c property setters work
Are 开发者_如何学JAVAmy two assumptions about properties correct?
@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
Yes; that is correct.
Note that the instance variable should be created
; it should start with a lowercase letter. I'd also recommend creationDate
.
It is recommended not to use properties in dealloc or init, so in the init method instead of doing self.propertyName = [NSDate date];
you should do fieldName = [[NSDate alloc] init];
the release in dealloc is fine though
More about it
精彩评论