Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectiveC: where to declare private instance properties?

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!

like image 961
hzxu Avatar asked Jul 03 '12 04:07

hzxu


People also ask

How do you declare an instance variable in Objective-C?

In Objective-C, instance variables are commonly created with @propertys. An @property is basically an instance variable with a few extra bonus features attached. The biggest addition is that Objective-C will automatically define what's called a setter and a getter for you automatically.

What are declared properties Objective-C?

The Objective-C declared properties feature provides a simple way to declare and implement an object's accessor methods.

What is synthesize in Objective-C?

@synthesize tells the compiler to take care of the accessor methods creation i.e it will generate the methods based on property description. It will also generate an instance variable to be used which you can specify as above, as a convention it starts with _(underscore)+propertyName.


2 Answers

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
like image 118
James Webster Avatar answered Oct 17 '22 01:10

James Webster


You dont have to declare your ivars in both the interface and the implementation.Because you want to make them private you can just declared them in the implementation file like so:

@implementation {

int firstVariable;
int secondVariable;
...
}
//properties and code for  your methods

If you wanted to, you can then create getter and setter methods so that you can access those variables.

The person you spoke to was right, though there is not any reason why you would NOT declare them the same way in the interface. Some books actually teach you that the @interface shows the public face of the class and what you have in the implementation will be private.

like image 36
AlexUseche Avatar answered Oct 16 '22 23:10

AlexUseche