4

With properties in obj-c, do we need to declare the instance variables?

Eg if my .h file looks like this:

@interface MyClass : NSObject {
}

@property (nonatomic, retain) NSNumber *someId;
@property (nonatomic, retain) NSDate *expires;
@property (nonatomic, retain) NSString *someString;

...

Is that fine? It compiles and works, is it the 'done thing' ? Or should i really be doing the below:

@interface MyClass : NSObject {
    NSNumber *someId;
    NSDate *expires;
    NSString *someString;
}

@property (nonatomic, retain) NSNumber *someId;
@property (nonatomic, retain) NSDate *expires;
@property (nonatomic, retain) NSString *someString;

...

Is there any difference in either of the above ways, if i plan to always use the property accessors?

Does the @synthesize take care of creating the instance vars for me?

Chris
  • 39,719
  • 45
  • 189
  • 235
  • Please [search before posting](http://stackoverflow.com/search?q=%5Bobjc%5D+property+declare+ivar) [1](http://stackoverflow.com/questions/5031230/) [2](http://stackoverflow.com/questions/3336922/) [3](http://stackoverflow.com/questions/4299487/) [4](http://stackoverflow.com/questions/4333797/) [5](http://stackoverflow.com/questions/4706816/) – jscs May 03 '11 at 02:38

2 Answers2

5

You understood correctly, @synthesize takes care of creating ivars for you. (That's a new feature of the runtime that's compatible with 64 bits Macs and iOS devices.)

What's nice with that, is that you can @property in your class extension and hide your ivars completely from the .h, separating completely the interface from the implementation.

You can also remove completely the '{}' from the .h, making it really clean.

gcamp
  • 14,622
  • 4
  • 54
  • 85
1

Found this in the apple docs:

With the modern runtime, if you do not provide an instance variable, the compiler adds one for you

Chris
  • 39,719
  • 45
  • 189
  • 235