0

Objective-C 2.0 introduced properties. While I personally think properties are nice addition to the language, I have seen a trend of making every instance variable as a property. Apple sample codes are no exceptions to this. I believe this is against the spirit of OOP, and since it exposes a lot more implementation details of a class to the client than they need to know.

What guidelines do you suggest for the proper usage properties in Objective C?

3 Answers 3

4

I make all my instance variables properties. That primary reason for that is that it makes memory management much easier and consistent. Making them public would go against good OO, so I always make them private using a category like this:

// File: ProjectManager.m:
@interface ProjectManager ()

@property (nonatomic, copy) NSString *slotID;
@property (nonatomic, retain) SubmitHandler *submitHandler;

@end

@implementation ProjectManager

@synthesize slotID, submitHandler;

- (void)dealloc
{
    self.slotID = nil;
    self.submitHandler = nil;
}
1
  • 1
    +1 for private properties.
    – user4595
    Oct 28, 2011 at 11:11
2

According to this page: "Objective-C “declared properties” feature provides a simple way to declare and implement an object’s accessor methods."

So properties are a way to declare and/or implement getter/setters.

Do you think getter/setters are "against the spirit of OOP"? If yes: go for immutable data structures, if no: i don't see a problem with properties.

1
  • Setters/Getters are definitely within the spirit of OOP. Properties simplify getters & setters. As a result people tend to declare properties for every single instance variable. Which is a bit annoying.
    – ab79
    Jan 13, 2011 at 13:20
1

I'm suggesting:

  1. Declare only those properties you really need to reach outside declared object scope. Otherwise - leave it only as instance variable.
  2. Declare properties read-only if you only need to read the property and not set it.
  3. More of a tip, but make sure you do not declare retained property for your custom object's delegate.
1
  • Also: where you don't want someone mutating your object's property behind your back, you should make that a copy property in the class.
    – user4051
    Nov 10, 2012 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.