views:

923

answers:

6

Hi all,

I'm trying to understand how strategies some folks use to distinguish instance vars vs. properties. A common pattern is the following:

@interface MyClass : NSObject {
    NSString *_myVar;
}

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

@implementation MyClass
@synthesize myVar = _myVar;

Now, I thought the entire premise behind this strategy is so that one can easily distinguish the difference between an ivar and property. So, if I want to use the memory management inherited by a synthesized property, I'd use something such as:

myVar = @"Foo";

The other way would be referencing it via self.[ivar/property here].

The problem with using the @synthesize myVar = _myVar strategy, is I figured that writing code such as:

myVar = some_other_object; // doesn't work.

The compiler complains that myVar is undeclared. Why is that the case?

Thanks.

+5  A: 

Properties are just setters and getters for ivars and should (almost) always be used instead of direct access.

Personally, I prefer to use the same name for the property as for the corresponding ivar:

@interface APerson : NSObject {
    NSString *name;
}

@property(readwrite) name;

@end

@implementation APerson
@synthesize name;
@end

@synthesize creates in this case those two methods (not 100% accurate):

- (NSString *)name {
    return [[name copy] autorelease];
}
- (void)setName:(NSString *)value {
    [value retain];
    [name release];
    name = value;
}

It's easy now to distinguish between ivars an getters/setters. The accessors have got the self. prefix. You shouldn't access the variables directly anyway.

You should be aware, that Apple reserves all variable names starting with a leading underscore for itself.


Your sample code doesn't work as it should be:

_myVar = some_other_object;      // _myVar is the ivar, not myVar.
self.myVar = some_other_object;  // works too, uses the accessors
Georg
+3  A: 

A synthesized property named prop is actually represented by two methods prop (returning the current value of the property) and setProp: (setting a new value for prop).

The self.prop syntax is syntactic sugar for calling one of these accessors. In your example, you can do any one of the following to set the property myVar:

self.myVar = @"foo"; // handles retain/release as specified by your property declaration
[self setMyVar: @"foo"]; // handle retain/release
_myVar = @"Foo"; // does not release old object and does not retain the new object

To access properties, use self.propname. To access instance variables use just the instance variable's name.

rincewind
+2  A: 

In general, I name my properties the same as my instance variables; this is the default assumption that the @property syntax makes. If you find you're fighting the defaults, you're doing it wrong (or your framework sux, which is not the case for Cocoa/Cocoa-touch in my opinion).

The compiler error you're getting is because property use always has to have an object reference, even inside your own class implementation:

self.stuff = @"foo"; // property setter
[stuff release]; // instance variable
stuff = @"bar"; // instance variable
return self.stuff; // property getter

I know that many Cocoa programmers disagree, but I think it's bad practice to use properties inside your class implementation. I'd rather see something like this:

-(void) someActionWithStuff: (NSString*) theStuff {
    // do something
    [stuff release];
    stuff = [theStuff copy];
    // do something else
}

than this:

-(void) someActionWithStuff: (NSString*) theStuff {
    // do something
    self.stuff = theStuff;
    // do something else
}

I prefer to do memory management as explicitly as possible. But even if you disagree, using the self.stuff form will clue in any experienced Objective-C programmer that you're calling a property rather than accessing an instance variable. It's a subtle point that's easy for beginners to gloss over, but after you've worked with Objective-C 2.0 for a while, it's pretty clear.

Don McCaughey
The problem with doing it as you describe is you leave yourself open to bugs when you duplicate the memory management code as you've shown (for example, your fitst version of someActionWithStuff will crash if you do [self someActionWithStuff:stuff]!). Further, if you change the behaviour of setStuff, you're left wondering where else you might need to apply the change.
Peter N Lewis
“… it's bad practice to use properties inside your class implementation.” No, it's not. Using the accessors (whether by property-access syntax or explicitly) causes KVO notifications for free. Hitting the instance variable directly means you have to post your own KVO notifications, which you *will* forget to do in at least one place.
Peter Hosey
If using accessors from inside the class implementation is fine, does that mean that you have @property accessors for _every_ ivar? On the one side this sounds e.g. for lazy-loading something in accessors or the automatic retain/release management of @synthesize. But then, wouldn't that mean that private ivars that contain internal states (such as maybe lock and condition objects) are exposed to other classes? (Accessors are methods and from what I remember, methods are always public in Objective-C)
Andreas
A: 

Don,

According to the "rules", you should call Release for every Copy, Alloc, and Retain. So why are you calling Release on stuff? Is this assuming it was created using Alloc, Copy, or Retain?

This brings up another question: Is it harmful to call Release on a reference to an object if it's already been released?

Edward An
Don is releasing the ivar stuff because a copy is made when it is assigned (see the following line). This is (more or less) the same beaviour as the @synthesized property setter when used with the copy (or similarly, retain) attribute. And yes, it is absolutely harmful to call release on a reference after you've called release, unless you have two ownerships of the object to release. See the memory management rules at <http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>.
Peter N Lewis
So now Releasing a reference pointer involves more than just the immediate Alloc, Copy, and Retain? Instead, references should be release prior to a new reference assignment (unless of course the self prop is used, which performs this under the covers)?This seems wrong. But please confirm as i chew on this more. Thanks!
Edward An
After a little bit of mental visualization, this makes sense. the reference count must be manually managed, hence the Release before assigning it a new ref.
Edward An
A: 

Since Apple reserves the _ prefix for itself, and since I prefer to make it more obvious when I am using the setter and when I am using the ivar, I have adopted the practive of using a prefix of i_ on my ivars, so for example:

@interface MyClass : NSObject {
    NSString *i_myVar;
}

@property (nonatomic, retain) NSString *myVar;

@synthesize myVar = i_myVar;

i_myVar = [input retain];
self.myVar = anotherInput;
[i_myVar release]

Since it is quite important to know when you are using the setter and when you are using the ivar, I find the explicitly different name is safer.

In your question, it should be:

self.myVar = @"Foo"; // with setter, equivalent to [self setMyVar:@"Foo"]

and

_myVar = some_other_object;  // direct ivar access - no memory management!

Remember that you should not use setters/getters in init/dealloc, so you need to do your direct ivar access (and careful memory management) iin those methods.

Peter N Lewis
+2  A: 

The problem with using the @synthesize myVar = _myVar strategy, is I figured that writing code such as:

myVar = some_other_object; // doesn't work.

The compiler complains that myVar is undeclared. Why is that the case?

Because the variable myVar is undeclared.

That statement uses the syntax to access a variable, instance or otherwise. As rincewind told you, to access a property, you must use either the property-access syntax (self.myVar = someOtherObject) or an explicit message to the accessor method ([self setMyVar:someOtherObject]).

Otherwise, you're attempting to access a variable, and since you don't have a variable named myVar, you're attempting to access a variable that doesn't exist.

Peter Hosey