通过私有属性初始化一个属性

Initializing a property through the private attribute

我正在通过 Big Nerd Ranch Guide 学习 Objective-C。 作者使用了一个商店,控制器可以从中获取一些数据来显示:

#import "BNRItemStore.h"
#import "BNRItem.h"

@interface BNRItemStore ()

@property(nonatomic) NSMutableArray *privateItems;

@end

@implementation BNRItemStore

+(instancetype)sharedStore {
    static BNRItemStore *sharedStore = nil;

    if (!sharedStore){
        sharedStore = [[BNRItemStore alloc] initPrivate];
    }
    return sharedStore;
}

-(instancetype)initPrivate {
    self = [super init];
    if (self) {
        _privateItems = [[NSMutableArray alloc] init];
    }
    return self;
}

我的问题是关于 _privateItems = [[NSMutableArray alloc] init]; 行:为什么我们初始化 _privateItems 而不是 privateItems

此致。

privateItems 是 属性 的名字。每个 属性 后面都有一个变量,默认名称为 _propertyName。在你的情况下是 _privateItems.

大多数时候,您会使用 属性 来设置值,如下所示:self.privateItems = [[NSMutableArray alloc] init]。但是,您不应该直接在 init 方法中设置属性,这就是作者将值直接设置为变量的原因。