How to initialize a property in iOS UITableViewController
initialization, ios, lazy-initialization, objective-c
Solution
If the values are not being set from the outside then they shouldn't be read/write properties. Make them read-only and use lazy loading in the "getter" method.
@interface GinkgoDeliveryOrdersTableViewController : UITableViewController
@property (nonatomic, readonly) PFQuery * query;
@property (nonatomic, readonly) NSArray * products;
@end
@implementation GinkgoDeliveryOrdersTableViewController
@synthesize query = _query;
@synthesize products = _products;
- (PFQuery *)query {
if (!_query) {
_query = ...
}
return _query;
}
Do the same for the `products` getter.
Note that in your original code there was no need for the `@synthesize` lines but in this updated code they are needed because otherwise the ivar wouldn't be auto generated due to the explicit getter method.
Problem
I am working on a `UITableViewController` ``` @interface GinkgoDeliveryOrdersTableViewController : UITableViewController @property PFQuery * query; @property NSArray * products; @end ``` How shall I initialize these two properties? Currently, I am doing lazy initialization: ``` @implementation GinkgoDeliveryOrdersTableViewController @synthesize query = _query; @synthesize products = _products; - (void) initQuery { _query = [PFQuery queryWithClassName:@"_Product"]; } - (void) initProducts { if(! _query) [self initQuery]; _products = [_query findObjects]; } ``` As a result, every time I want to use these two properties, I have to do something like this: ``` if(! self.products) [self initProducts]; ``` and ``` if(! self.query) [self initQuery]; ``` I feel I am doing something wrong here. Is there a cleaner way to do this? Thank you very much!