在目标 C 中返回 null 的属性的延迟实例化



我不明白为什么我对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]);
}

因为您直接访问实例变量_someItems,而不是使用其自定义 getter,在那里它是延迟初始化的。

您应该执行[self.someItems description]进行延迟初始化。

我在项目中尝试了相同的代码。如果我打印

NSLog(@"Some items %@", [self.someItems description]);

它工作和打印 -

Some items {
    1 = A;
    2 = B;
    3 = C;
    4 = D;
    5 = E;
    6 = F;
    7 = G;
    8 = H;
}

最新更新