Search code examples
objective-cpropertiesprivate

Creating private properties in Objective-C


In Objective-C, there's a sort of hackish way to create private methods, in the .m file:

@interface FooClass (PrivateMethods)
- (void) doBar:(id)barAction withBaz:(id)bazAction;
@end

This works great for methods. I tried to do the same with a property:

@interface BarClass (PrivateMethods)
@property (nonatomic, strong) BazObject *myBaz;
@end

@implementation BarClass
@synthesize myBaz = _myBaz;
[...]
@end

This brought a compile warning: Property declared in category 'PrivateMethods' cannot be implemented in class implementation. I tried to move my property into a category:

@implementation BarClass (PrivateMethods)
@synthesize myBaz = _myBaz;
@end

Then: @synthesize is not allowed in a category's implementation.

The obvious answer is "quit trying, just use ivars", but I've been told by people at Apple that they've (personally) moved to entirely using properties. The safety they bring (like safety on a gun, harder to shoot yourself in the foot) makes me all happy inside, so is there any way to do this without resorting to naked ivars?


Solution

  • Use a class extension instead of a category (note the absence of a category name inside the parentheses):

    @interface BarClass ()
    @property (nonatomic, strong) BazObject *myBaz;
    @end
    
    @implementation BarClass
    @synthesize myBaz = _myBaz;
    [...]
    @end
    

    You might want to read this question (and answers) as well: Does a private @property create an @private instance variable?