Specific performance and behaviour difference using properties or accessing the ivars directly.
For Global variables, What is the difference between using this:
@interface myClass (){
UIImageView *myView;
}
-(void)loadView{
[super loadView];
myView = [[UIImageView alloc] initWithFrame:CGrectMake(0,0,100,100)];
}
And doing this:
@interface myClass (){
}
@property (nonatomic, strong) UIImageView *myView;
@synthesize myView = _myView;
-(void)loadView{
[super loadView];
myView = [[UIImageView alloc] initWithFrame:CGrectMake(0,0,100,100)];
}
What benefits can we have with every approach? What are the reasons to recommend to always uses properties?
In the first case, your instance variable (or ivar) myView
is private to the class and cannot be accessed by another class.
In the second case, you have provided a property that allows other classes to access your ivar via synthesized accessors. The alternative to declared properties is to write your own accessor methods. The @synthesize
notation does that for you.
See Apple documentation on declared properties
ALWAYS create a
@property
for every data member and useself.name
to access it throughout your class implementation. NEVER access your own data members directly.
- Properties enforce access restrictions (such as readonly)
- Properties enforce memory management policy (retain, assign)
- Properties are (rarely) used as part of a thread safety strategy (atomic)
- Properties provide the opportunity to transparently implement custom setters and getters.
- Having a single way to access instance variables increases code readability.
You can also check out: The Code Commandments: Best Practices for Objective-C Coding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With