我想要一个带有一些属性的单例类。目前,我声明如下:
@interface MyClass : NSObject
@property(nonatomic, strong)NSString *myString;
+(MyClass *)sharedInstance;
+(NSString *)myString;
有没有办法在没有为每个属性编写getter的情况下拥有类级访问器?
答案 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