Question

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
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top