我不明白为什么我的NSDictionary
懒惰实例化正在返回NULL
。
我在很多教程中已经多次看到这种惰性实例化的方法。我做错了什么?
@interface ViewController ()
@property (nonatomic, strong) NSDictionary* someItems;
@end
@implementation ViewController
-(NSDictionary*) someItems {
if (!_someItems) {
_someItems = @{@"1" : @"A",
@"2" : @"B",
@"3" : @"C",
@"4" : @"D",
@"5" : @"E",
@"6" : @"F",
@"7" : @"G",
@"8" : @"H"};
}
return _someItems;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"Some items %@", [_someItems description]);
}
答案 0 :(得分:4)
因为您正在直接访问实例变量_someItems
而不是使用其自定义getter,因此它会被懒惰地初始化。
您应该[self.someItems description]
进行延迟初始化。
答案 1 :(得分:0)
我在我的项目中尝试了相同的代码。如果我打印
NSLog(@"Some items %@", [self.someItems description]);
它起作用并打印 -
Some items {
1 = A;
2 = B;
3 = C;
4 = D;
5 = E;
6 = F;
7 = G;
8 = H;
}