Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @property and ivar in Xcode 4.5

Previously I have always seen example of use of properties and iVars like this...

Inside SomeClass.h

@interface SomeClass : NSObject {
    NSString *_someString;
}

@property NSString *someString;

@end

Then in SomeClass.m

#import "SomeClass.h"

@implementation SomeClass

@synthesize someString = _someString;

@end

More recently (in the WWDC 2012 videos) I've heard that we no longer need @synthesize and it's recommended to just use the @property without it's associated iVar.

So the above would change to...

SomeClass.h

@interface SomeClass : NSObject

@property NSString *someString;

@end

SomeClass.m

#import "SomeClass.h"

@implementation SomeClass

@end

This is just using the @property and no ivar. This makes sense and I have been using it.

However, I have also seen examples of...

SomeClass.h

@interface SomeClass : NSObject

@end

SomeClass.m

#import "SomeClass.h"

@interface SomeClass () {
    NSString *someString;
}

@end

@implementation SomeClass

@end

In this they just have a private iVar and no @property.

So what's the difference? I understand that the @property gives the accessor methods too but you don't have to override the accessor methods. You can just use default accessors.

So when would you use @property and not an ivar and when would you use just an ivar and not a @property? And why wouldn't you just get rid of ivars completely and just use @properties? If they need to be private then just use them inside the interface extension in the .m.

Quick edit in response to an answer about memory management. I'm using ARC and for me it would seem that I have more control over memory management with using strong and weak @properties than I do with using iVars.

I hope the question is clear enough.

Thanks

like image 676
Fogmeister Avatar asked Oct 18 '12 13:10

Fogmeister


1 Answers

In general you can always use properties. If you have "assign" property you can use ivar beause you don't need any memory management in your getters/setters. But if you should retain objects it is just inconvinient to use ivars because you have to manually retain/release them while properties do that for you.

Also If you use ivars you don't have control over setting/getting values. In general it is a bad practive to use public fields instead of getters or setters. For example it is not ok if you can set negative value for field that store person's age.

And you can't use KVO with ivars

like image 112
igoris Avatar answered Nov 12 '22 09:11

igoris