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
someString
property with a default backing iVar named_someString
and a second iVar that has no connection to the property but is namedsomeString
just to cause pain. :-) – Wenoa@property
gives you the ability to use KVO where a regular iVar does not. Other than what you've already mentioned, I don't know of any other advantages/disadvantages. – Migrant