5

What are the differences (if any) between the following Objective-c 2.0 code snippets:

// in MyClass.h
@interface MyClass
@private
    NSString *myString;
@end

and

// in MyClass.m
@interface MyClass ()
@property (nonatomic, copy) NSString *myString;
@end

@implementation MyClass
@synthesize myString;
@end
SundayMonday
  • 19,147
  • 29
  • 100
  • 154

1 Answers1

6

The ivar (first one) is a plain variable that cannot be accessed out of the scope of an implementation of the interface it's created in (if @private directive is used) and has no synthesized accessor methods.

The property (second one) is a wrapped ivar and something that can always be accessed via instantiating a class and has accessor methods synthesized (if @synthesize directive is being used)

MyClass *class = [[MyClass alloc] init];
[class setMyString:@"someString"]; //generated setter
NSString *classString = [class myString]; //generated getter
Eugene
  • 10,006
  • 4
  • 37
  • 55
  • In the second case I don't think myString's synthesized getter/setter can be accessed outside of the implementation scope. Notice they are in a class extension inside of the implementation file. – SundayMonday Dec 22 '11 at 17:45
  • Sorry, I missed that part. The latter one is considered to be in a private section (the same as Apple's private API's like -recirsiveDescription of UIView). But they still can be accessed via accessor methods, though compiler will generate warnings. The first one will not be accessible as compiler will generate errors. – Eugene Dec 22 '11 at 18:32