Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C: Why do we declare ivars in the .h member area if @property seems to do it automatically?

In implementing an interface it seems the common method in tutorials and literature is to declare an ivar and then set the @property then @synthesize.

@interface MyClass : NSObject {
NSString *myString;
}

@property (nonatomic, retain) NSString *myString;
@end

However, omitting the explicit declaration and just putting @property has the same effect.

@interface MyClass: NSObject {
}

@property (nonatomic, retain) NSString *myString;
@end

So how come most people use @property and an explicit declaration? Is it bad form not to?

like image 566
anixon604 Avatar asked Apr 05 '11 17:04

anixon604


People also ask

How do I declare iVar in Objective C?

For a private/protected variable, use iVar; for a public variable, use property. If you want to use the benifit of property attributes for a private variable, like retain, nonatomic etc., declare the property in the implementation file as a private property. For an iVar, you can use @private , @protected and @public .

What is iVar in programming?

An opaque type that represents an instance variable.


2 Answers

It used to be necessary. There are two different versions of the Objective-C runtime: a 32-bit-only "legacy" runtime (the old one) and a 32/64-bit runtime (the new 32-bit runtime is only used on iOS devices and for the iOS simulator).

I think the only place this is still necessary is when you're running the app in 32-bit mode (either 10.5 or 10.6). Everywhere else (64-bit Leopard, 64-bit Snow Leopard, Lion, iOS) uses the newer runtime that has "automatic ivar synthesis", and the resulting ivars are referred to as "synthesized ivars".

like image 72
Dave DeLong Avatar answered Oct 15 '22 10:10

Dave DeLong


Some platforms support synthesized instance variables, some don't. Explicitly declaring instance variables makes your code valid in more places, and it used to be outright necessary until very recently, so people still do it. In a few years, they probably won't anymore.

like image 44
Chuck Avatar answered Oct 15 '22 10:10

Chuck