问题
what's the auto-gen'd getter and setter look like for the following property value?
... in .h
@interface MyClass : NSObject {
@private
NSString *_value;
}
@property(retain) NSString *value;
... in .m
@synthesize value = _value;
what if I change the property to be
@property(retain, readonly) NSString *value;
specifically I am interested in the atomic part of the story, plus the retain, and if possible, detailed code would be more clear as to what's going exactly going on behind the scene.
回答1:
They would look something like:
- (NSString*) value
{
@synchronized(self) {
return [[_value retain] autorelease];
}
}
- (void) setValue:(NSString*)aValue
{
@synchronized(self) {
[aValue retain];
[_value release];
_value = aValue;
}
}
If you change the property to readonly, no setter is generated. The getter will be identical.
回答2:
if you do not specify the readonly
with property declaration then Compiler will produce the getter and setter and be as below.
setter ---> setValue:
[self setValue:@"setter"];
getter -----> Value,
NSString* myValue = [self Value];
Compilar will not produce the setter function for the property which you have declared with readonly
.
atomic
are thread safe whereas nonatomic
is not.
来源:https://stackoverflow.com/questions/8382523/setter-and-getter-for-an-atomic-property