Just started diving into Objective-C and IOS development and was wondering when and the correct location I should be declaring variables/properties. The main piece of code i need explaining is below:
Why and when should i be declaring variables inside the interface statement and why do they have the same variable with _ and then the same one as a property. And then in the implementation they do @synthesize tableView = _tableView (I understand what synthesize does)
Thanks 🙂
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
UITableView *_tableView;
UIActivityIndicatorView *_activityIndicatorView;
NSArray *_movies;
}
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicatorView;
@property (nonatomic, retain) NSArray *movies;
Best Answer
First of all, there is no need to declare the instance variables for properties as the statement
is actually generating an implicit variable named _iVar for you.
You would create properties when you want them to be accessible outside the class like
Properties also relieve you of writing your own getters & setters and take care of much of memory management themselves. Here is something you might wanna read plus other articles linked within the post.
http://cocoawithlove.com/2008/08/in-defense-of-objective-c-20-properties.html