在Objective-C中初始化静态变量

Ste*_*eod 4 idioms objective-c

在Objective-C类中,我想只将文本文件的内容加载到NSString中,以便该类的所有实例都可以使用它.

在Java世界中,我多年来了解到,如果你不使用经过验证的成语,就很容易在线程安全方面出现这种错误.所以我想确保使用正确的习语.

你能告诉我一个Objective-C类的例子吗?

这是我开始时的空课......

@interface TestClass : NSObject
- (NSString *)doSomething:(NSUInteger)aParam;
@end

@implementation TestClass {
}

- (id)init {
    self = [super init];
    if (self) {

    }
    return self;
}

- (NSString *)doSomething:(NSUInteger)aParam {
     // something with shared NSString loaded from text file, 
     //  depending on the value of aParam
     return @""; 
}
@end
Run Code Online (Sandbox Code Playgroud)

das*_*ght 7

在Objective C中处理静态属性的惯用方法是将它们隐藏在类方法(带有方法+)之后.将您的字符串声明为static类方法实现的内部,并dispatch_once用于初始化:

+ (id)stringFromFile {
    static dispatch_once_t once;
    static NSString *sharedString;
    dispatch_once(&once, ^{
        sharedString = [NSString
            stringWithContentsOfFile:@"MyFile"
            encoding:... // ...supply proper parameters here...
            error:...];
    });
    return sharedString;
}
Run Code Online (Sandbox Code Playgroud)

这种设置静态对象的方法是线程安全的.在sharedString将被初始化一次,即使该方法是从多个线程同时调用.

现在,您可以通过调用从任何地方获取字符串[MyClass stringFromFile].