Ra1*_*den 4 initialization objective-c lazy-initialization ios
我正在努力 UITableViewController
@interface GinkgoDeliveryOrdersTableViewController : UITableViewController
@property PFQuery * query;
@property NSArray * products;
@end
Run Code Online (Sandbox Code Playgroud)
我该如何初始化这两个属性?目前,我正在做懒惰的初始化:
@implementation GinkgoDeliveryOrdersTableViewController
@synthesize query = _query;
@synthesize products = _products;
- (void) initQuery {
_query = [PFQuery queryWithClassName:@"_Product"];
}
- (void) initProducts {
if(! _query)
[self initQuery];
_products = [_query findObjects];
}
Run Code Online (Sandbox Code Playgroud)
因此,每次我想使用这两个属性时,我都必须这样做:
if(! self.products)
[self initProducts];
Run Code Online (Sandbox Code Playgroud)
和
if(! self.query)
[self initQuery];
Run Code Online (Sandbox Code Playgroud)
我觉得我在做错了.有更清洁的方法吗?非常感谢你!
如果没有从外部设置值,则它们不应该是读/写属性.将它们设为只读并在"getter"方法中使用延迟加载.
@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;
}
Run Code Online (Sandbox Code Playgroud)
对products吸气剂做同样的事情.
请注意,在原始代码中不需要@synthesize行,但在此更新的代码中需要它们,因为否则由于显式的getter方法而不会自动生成ivar.
| 归档时间: |
|
| 查看次数: |
7437 次 |
| 最近记录: |