OWolf
OWolf

Reputation: 5122

objective C, properties vs ivars

I suspect that this question has been asked and answered, but I have read many posts on it and I'm not totally clear on the answer.

I generally find it quite convenient to declare private variables as instance variables in the implementation section of my.m files like so:

@implementation ViewController {
    int someNum;
    NSObject *myObj;
}

Is this ok, and or best practice currently? Do I need to be declaring properties instead for some reason?

Upvotes: 3

Views: 757

Answers (1)

Warren Burton
Warren Burton

Reputation: 17372

One technique is to declare a class extension within the .m

@interface MyViewController() {

NSInteger someNumber;
NSObject *myObject;

}

@end

@implementation MyViewController

-(void)someMethod {

someNumber++;

}

@end

Assuming ARC you will get strong references to object types. Thats not any different from what you did. Its just separating interface and implementation more clearly and also lends itself to patterns such as Private Implementation

However with properties you get the opportunity to manipulate the accessors and also you get KVC for free.

@interface MyViewController() {

    NSInteger someNumber;

}

@property (copy,readwrite,nonatomic) NSObject *myObject;

@end

@implementation MyViewController

-(void)someMethodWhichNeedsACopy:(NSObject *)aobj {

self.myObject = aobj; //free copies , no smudging!

}

@end

And in addition allows you to override

-(void)setMyObject:(NSObject *)aobj

-(NSObject *)myObject

or just access the implicit private ivar

[_myObject doSomethingCool]; 

_myObject.thing = something;

or use the KVC given to you by the generated accessors

[myViewControllerInstance addObserver:someOtherObject forKeyPath:@"myObject" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL]

after which someOtherObject will receive messages of the form

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

In short. What you are doing is not wrong but there are other techniques and tools to explore with which you can do more stuff.

Upvotes: 3

Related Questions