Reputation: 107
I have gone through many questions asked here and on other forums regarding @property in Objective-C. But a question pops up every now and then..
Do we need i-vars to support properties?
Please go through the following code -
the RootViewController.h file :-
#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController {
}
@property (nonatomic, retain) NSMutableArray *arrTest;
@end
The RootViewController.m is as follows -
#import "RootViewController.h"
@implementation RootViewController
@synthesize arrTest;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
self.arrTest = [[[NSMutableArray alloc] init] autorelease];
[arrTest addObject:@"Object1"];
[arrTest addObject:@"Object2"];
[arrTest addObject:@"Object3"];
[arrTest addObject:@"Object4"];
[arrTest addObject:@"Object5"];
NSLog(@"arrTest :- \n%@",arrTest);
NSLog(@"self.arrTest :- \n%@",self.arrTest);
[self.arrTest addObject:@"Object6"];
[self.arrTest addObject:@"Object7"];
[self.arrTest addObject:@"Object8"];
[self.arrTest addObject:@"Object9"];
[self.arrTest addObject:@"Object10"];
NSLog(@"arrTest :- \n%@",arrTest);
NSLog(@"self.arrTest :- \n%@",self.arrTest);
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
As you can see, I have not created an instance variable to support the property.
From this I am assuming that a variable is internally created as I can access it by just saying
[arrTest addObject:@"Blah Blah"];
If that is the case, then why do we need to create instance variable if we are about to declare properties?
Upvotes: 2
Views: 613
Reputation: 15857
If your @property
declaration references an undeclared ivar, the Objective-C runtime will dynamically synthesize the ivar for you.
This requires that you compile for iPhone OS or 64-bit Mac OS X. If you want to target Mac OS X i386 or PPC you have to declare your ivars explicitly.
There is a good article about this here. http://cocoawithlove.com/2010/03/dynamic-ivars-solving-fragile-base.html
Upvotes: 3