SeNeO
SeNeO

Reputation: 417

Property with custom setter but default getter

What is the best practice?

and why prefer one of this solution rather another.

Upvotes: 0

Views: 289

Answers (1)

Bryan Chen
Bryan Chen

Reputation: 46598

In most of the cases, you just need to provide implementation for setter and declare the property as nonatmoic. This will generate ivar with underscore prefix and you need to set the value in setter method.

You don't normally need to override getter unless you have special logic in getter or the property need to be atomic.

If you do want to provide getter (along with setter), you may need a backend ivar either by declare it in @implementation{ /*here*/ } or use @synthesize to generate one.

In case for atomic property:

@interface MyClass : NSObject
@property (atomic) id object; // atomic is default attribute 
@end
@implementation MyClass
@synthesize object = _object; // to create ivar
- (id)object {
@synchronized(self) { // or use lock / atomic compare-and-swap
    return _object;
}
}
- (void)setObject:(id)obj {
@synchronized(self) {  // or use lock / atomic compare-and-swap
    _object = obj;
}
}

@end

Upvotes: 1

Related Questions