关于懒加载的定义
懒加载就是数据在用到的时候进行加载一次,不用的时候就不需要加载了。通常写在哪个位置呢?——-get方法中。也就是咱们常说的重写,对他的get方法重写。
- (NSArray *)shops
{
if (_shops == nil) {
_shops = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shops" ofType:@"plist"]];
}
return _shops;
}
注意此处用的是_shops形式,不能使用self.shops由于点是get方法会导致死循环出现。
注意关于控件的懒加载方法,如下:
- (UILabel *)nameLabel
{
if (_nameLabel == nil) {
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.font = [UIFont systemFontOfSize:11];
nameLabel.textAlignment = NSTextAlignmentCenter;
nameLabel.backgroundColor = [UIColor redColor];
[self addSubview:nameLabel];
_nameLabel = nameLabel; //将传入的对象保留
}
return _nameLabel;
}
所以关于懒加载指的是对象,而不是简单的对一个对数据进行处理的数组。对象可以是任何一个控件,可以是imageview、button这些都可以。