Property vs. instance variable

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:

  • How to convert a view-based iOS project an universal build?
  • What is the most efficient way to count number of word in NSString without using regex?
  • Hide dots from UIPageViewController
  • Breaking retain cycle with strong/weak self
  • UIButton as UINavigationbar button
  • iPhone UIView Animation Best Practice
  • 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.

    7 Solutions Collect From Internet About “Property vs. instance variable”

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

    @interface APerson : NSObject {
        // NSString *_name;           //  necessary for legacy runtime
    }
    
    @property(readwrite) NSString *name;
    
    @end
    
    @implementation APerson
    @synthesize name;                 // use name = _name for legacy runtime
    @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 and getters/setters. The accessors have got the self. prefix. You shouldn’t access the variables directly anyway.


    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
    

    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.

    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, be it an instance variable or some other kind. 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.

    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,

    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?

    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.

    what’s wrong with simply using

    @interface MyClass : NSObject
    @property NSString *prop;
    @end
    

    nonatomic and retain are not required, retain is the default, and atomic/nonatomic isn\t important unless XCode tells you with a warning.

    it is NOT necessary to declare the iVar, one will be created for you named _prop, if you really want to use one (i don’t see why to be honest)

    @synthesize is NOT required.

    when (and you should) using ARC you don’t have to bother with retain and release either.

    keep it simple !

    furthermore, if you have a method like this one

    - (void)aMethod:(NSString*)string
    {
        self.prop = string;
        // shows very clearly that we are setting the property of our object
    
        _aName = string;
        // what is _aName ? the _ is a convention, not a real visual help
    }
    

    i would always use properties, more flexible, easier to read.