在单例类中实现类级属性访问器的最快方法是什么?

时间:2015-03-23 13:48:08

标签: objective-c properties

我想要一个带有一些属性的单例类。目前,我声明如下:

@interface MyClass : NSObject

@property(nonatomic, strong)NSString *myString;

+(MyClass *)sharedInstance;
+(NSString *)myString;

有没有办法在没有为每个属性编写getter的情况下拥有类级访问器?

1 个答案:

答案 0 :(得分:0)

我通常以这种方式实现单身:

Singleton.h

@interface Singleton : NSObject

+ (Singleton *)sharedInstance;

@property (nonatomic) NSString *myProperty;

@end

Singleton.m

static Singleton *sharedInstance;

@implementation Singleton

+ (Singleton *)sharedInstance {
    if (!sharedInstance) {
        sharedInstance = [[Singleton alloc] init];
    }
    return sharedInstance;
}

- (id)init {
    if (self = [super init]) {
        self.myProperty = @"Hello World";
    }
    return self;
}

呼叫:

NSLog(@"My Property: %@", [Singleton sharedInstance].myProperty);

但听起来你不想每次都说[Singleton sharedInstance]。它是一个延伸,但你可以试试这个:

Singleton.h

@interface Singleton : NSObject

@property (nonatomic) NSString *myProperty;

@end

static Singleton *singleton;

static inline Singleton *sharedInstance() {
    if (!singleton) {
        singleton = [[Singleton alloc] init];
    }
    return singleton;
}

Singleton.m

@implementation Singleton

- (id)init {
    if (self = [super init]) {
        self.myProperty = @"Hello World";
    }
    return self;
}

@end

现在您只需致电sharedInstance().myProperty