Search code examples
objective-cpropertiesinstance-variables

I do not understand ways of declaring instance variable in the code


I do not quite understand the way of declaring instance variable and property. Can someone explain in detail the difference of the two codes below? In the second method, if I use _name for instance variable, is it the same function as the way declaring name in first code? Thanks!

First Code:

//  OrderItem.h
#import <Foundation/Foundation.h>

@interface OrderItem : NSObject

{

  @public NSString *name;

}

-(id) initWithItemName: (NSString *) itemName;

@end


//  OrderItem.m
#import "OrderItem.h"

@implementation OrderItem

-(id) initWithItemName: (NSString *) itemName {

     self = [super init];

      if (self) {

          name = itemName;

         NSLog(@"Initializing OrderItem");
   }

     return  self;

   }

@end

Second Code:

//  OrderItem.h
#import <Foundation/Foundation.h>

@interface OrderItem : NSObject

 @property (strong,nonatomic) NSString *name;

-(id) initWithItemName: (NSString *) itemName;

@end


//  OrderItem.m
#import "OrderItem.h"

@implementation OrderItem

-(id) initWithItemName: (NSString *) itemName {

     self = [super init];

      if (self) {

          _name = itemName;

         NSLog(@"Initializing OrderItem");
   }

     return  self;

   }

@end

Solution

  • In the first case you have declared an instance variable (usually called an ivar in Objective-C).

    In the second case you have declared a property. A property is a set of two methods, a getter and a setter, usually accessed using dot notation, e.g. self.name. However, an ivar is automatically synthesized for the property with the name _name. That instance variable is what you are accessing in your init.

    You can actually change the name of the ivar using @synthesize name = _myName or not have it at all (if you declare the getter and setter manually, no ivar will be synthesized).

    Objective-C properties are a rather complicated topic so don't worry if you don't understand it immediately.