0

In implementation file, all properties are indicated as private.
So what are the differences between these:

  1. MyObj.m

@interface MyObj ()

@property (nonatomic, strong) NSString *name;

@end

@implementation MyObj

@synthesize name = _name;

// Some other codes to use "name" like self.name or _name

@end


2. MyObj.m


@implementation MyObj
{
    NSString *_name;
}

// Some other codes to use _name

@end
Luca
  • 9,259
  • 5
  • 46
  • 59
Kevin
  • 1,147
  • 11
  • 21
  • possible duplicate of [Property vs. instance variable](http://stackoverflow.com/questions/719788/property-vs-instance-variable), along with about 800 other questions. See the sidebar ---> – jscs Oct 21 '12 at 18:19

2 Answers2

3

In the first example you get the accessors created for you

- (NSString *)name;
- (void)setName:(NSString *)name;

Also note that in newer versions of Xcode the @synthesize is implicit.

In the second example you just have an ivar created.

Unless you have a special case it's normally better to use accessors as it gives you more flexibility in the future.

Paul.s
  • 38,494
  • 5
  • 70
  • 88
  • agree with your saying "it gives you more flexibility in the future". and I want to ask another question: if I use property instead of ivar, when should I use self.name and when should I use _name? (assume that I synthesize name = _name) – Kevin Oct 21 '12 at 12:06
  • 1
    Just like most things in programming "it depends". I tend to only use `_name` if I override accessors or the init/dealloc method. So only places where I either need direct access as to not cause a recursive loop or places where I want to ensure I can get/set the value without causing any side effects. – Paul.s Oct 21 '12 at 15:23
  • You always want to use the ivar directly (not via a getter/setter method) in init and dealloc because getters and setters can be overridden by subclasses and those overrides could introduce behaviors that aren't safe at init and dealloc time. Outside those two places, I tend to use the getters/setters unless I have a very specific reason not to. Another thing worth mentioning is that using @property will get you certain KVC/KVO behaviors you won't get with just an ivar. – ipmcc Nov 04 '12 at 15:01
2

I would suggest that you always use @property's for all your class's data members. They have memory management built into so you don't have to worry about that. Properties also add syntactical sugar for using objects of that class. So if had an obj of your class MyObj I could just do

obj.name = @"brianSan";

which would be the exact same thing as

[obj setName: @"brianSan"];

Also, accessing name within obj could be accomplished through obj.name, which is the same thing as [obj name];

When you have to access methods within objects of objects, it becomes easier to look at obj.prop.subprop.subsubprop rather than [[[obj prop] suprop] subsubprop]

brianSan
  • 545
  • 6
  • 17