views:

272

answers:

3

Do properties in Objective-C 2.0 require a corresponding instance variable to be declared? For example, I'm used to doing something like this:

MyObject.h

@interface MyObject : NSObject {
NSString *name;
}
@property (nonatomic, retain) NSString *name;
@end

MyObject.h

@implementation
@synthesize name;
@end

However, what if I did this instead:

MyObject.h

@interface MyObject : NSObject {
}
@property (nonatomic, retain) NSString *name;
@end

Is this still valid? And is it in any way different to my previous example?

A: 

You must declare the instance variable. Your first example is the only way I'm aware of that is valid.

raidfive
A: 

You don't have to provide an instance variable. You need some place to store the value (unless it is dynamic) so there is usually an instance variable for every property.

In your second example, where would you actually store the name?

If you don't have an instance variable for the property you can't use the synthesized setter/getter and have to write your own. You still have to have a place to store the value or have some way of saving and retrieving it (ie: NSUserDefaults, a file, ...).

Here is the code @synthesize name; generates for you and you can see it uses the name instance variable:

-(void)setName:(NSString*)newName {
    [newName retain];
    [name release];
    name = newName;
}

-(NSString*)name {
    return [[name retain] autorelease];
}

With your second example, without the instance variable, we could implement like this:

@implementation MyObject
@dynamic name;

-(void)setName:(NSString*)newName {
    [[NSUserDefaults standardUserDefaults] setObject:newName forKey:@"name_key"];
}

-(NSString*)name {
    return [[NSUserDefaults standardUserDefaults] stringForKey:@"name_key"];
}
progrmr
+4  A: 

If you are using the Modern Objective-C Runtime (that's either iOS 3.x or greater, or 64-bit Snow Leopard or greater) then you do not need to define ivars for your properties in cases like this.

When you @synthesize the property, the ivar will in effect be synthesized also for you. This gets around the "fragile-ivar" scenario. You can read more about it on Cocoa with Love

jbrennan