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



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

@interface MyClass : NSObject
@property(nonatomic, strong)NSString *myString;
+(MyClass *)sharedInstance;
+(NSString *)myString;

有没有一种方法可以在不为每个属性编写getter的情况下使用类级访问器?

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

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

最新更新