需要注意:重写get方法时,先判断对象当前是否为空,为空的话再去实例化对象
@interface ViewController () @property (nonatomic, strong) NSArray *shopData; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _shopData = [NSArray arrayWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"shop" ofType:@"plist"]]; } @end
- (void)viewDidLoad { [super viewDidLoad]; } - (NSArray *)shopData { if (!_shopData) { _shopData = [NSArray arrayWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"shop" ofType:@"plist"]]; } return _shopData; } @end
注意掉坑:
在实现懒加载的时候,getter方法不要不要使用self.shopData方式来访问,要采_shopData方式来访问。如果如果使用点语法来访问getter方法,会形成死循环,因为使用点语法的来访问getter方法时,会继续调用这个方法,形成死循环!!!!
总之,懒加载中,getter方法方法使用_shopData方式访问。setter方法可以使用self.shopData = ?或_shopData = ?
原文:http://www.cnblogs.com/KeenLeung/p/5075872.html