Reputation: 21
I looked up my current problem on stackoverflow and many other website outlets, but I am a little confused to be quite honest. Should I only use properties when another class needs access to it and ivars when it is being used for only my private class? This is what I am getting so far, although I did hear some other things about when to use ivars and properties. I am just trying to keep my code clean and more modern. Any clarification will be appreciated.
Upvotes: 1
Views: 144
Reputation: 13343
In my opinion - you should only use properties, which are backed by an ivar if you didn't override the getter and the setter.
You should declare them in the public interface to make them public, and declare them in the private interface, that's right, to make them private.
There are many advantages to this, some are:
Within your class, you should almost always access your properties through the getter/setter unless:
Here's an example of how of some of the following points:
@interface SomeObject : NSObject
@property (strong, nonatomic) NSMutableArray * objects;
@property (readonly, nonatomic, getter=isActive) BOOL active; // Public read-only
@end
@interface SomeObject()
@property (readwrite, nonatomic, getter=isActive) BOOL active; // Can be updated internally
@property (nonatomic, getter=isVisible) BOOL visible;
@end
@implementation SomeObject
- (NSMutableArray)objects {
if (!_objects) {
_objects = [NSMutableArray array]; // Lazy instantiate when first accessed
}
return _objects;
}
- (BOOL)isActive {
return _isActive && self.isVisible; // Cannot be active if not visible
}
- (BOOL)setActive:(BOOL)active {
self.visible = active; // Keep visibility same as active
_active = active;
}
-(BOO)setVisible:(BOOL)visible {
_visible = visible;
// perform animation or something else...
}
@end
Any of this cannot be achieved using ivars.
Upvotes: 0
Reputation: 81856
This is a very opinion based topic. So I'm trying to stay with uncontroversial facts and advice:
NSString
, NSArray
et al. (copy
).atomic
).The actual decision whether or not to use ivars in the implementation is a matter of personal preference. It is affected by many subtle details from code style.
Upvotes: 3
Reputation: 16650
You should use declared properties inside and outside your class. Most developers say that you should only set the ivar behind a property in initializers. (I do not agree and use setters and getters in this case, too, but I'm in minority.)
Upvotes: -2