ObjectiveC: where to declare private instance properties?

hzxu picture hzxu · Jul 3, 2012 · Viewed 8.1k times · Source

I have the following class interface:

@interface MyClass : NSObject

@property int publicProperty;

@end

then the implementation:

@interface MyClass() // class extension

- (void)privateMethod; // private methods

@end

@implementation MyClass {
    int _privateProperty;
}

@property int privateProperty = _privateProperty;

@end

this is what the Apple guy showed in WWDC, but is there any reason for NOT putting _privateProperty in class extension like:

@interface MyClass() // class extension
{
    int _privateProperty;
}

- (void)privateMethod; // private methods

@end

Thanks!

Answer

James Webster picture James Webster · Jul 3, 2012

I usually "force" private with an extension in the implementation

In your header

@interface MyClass : NSObject
{
}

@property (nonatomic, assign) int publicProperty;

@end

In your implementation file:

@interface MyClass ()
@property (nonatomic, assign) int privateProperty;
@end


@implementation MyClass
@synthesize privateProperty;
@synthesize publicProperty;

@end