setter and getter for an atomic property

可紊 提交于 2019-12-04 15:31:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!