Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between private instance variable and property in class extension (Objective-c 2.0)

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
like image 703
SundayMonday Avatar asked Dec 22 '11 17:12

SundayMonday


People also ask

What is the difference between property and instance variable?

A property can be backed by an instance variable, but you can also define the getter/setter to do something a bit more dynamic, e.g. you might define a lowerCase property on a string which dynamically creates the result rather than returning the value of some member variable.

What is the difference between a class variable and an instance variable?

They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to others. Class Variable: It is basically a static variable that can be declared anywhere at class level with static.

What are private instance variables?

Instance variables are declared right after the class declaration. They usually start with private then the type of the variable and then a name for the variable. Private means only the code in this class has access to it. The Person class declares 3 private instance variables: name, email, and phoneNumber.

What is the difference between category and extension in Objective C?

Category and extension both are basically made to handle large code base, but category is a way to extend class API in multiple source files while extension is a way to add required methods outside the main interface file.


1 Answers

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
like image 88
Eugene Avatar answered Oct 31 '22 12:10

Eugene