plistファイルから辞書項目を読み込む小さなクラスを作成しました。 getSettingForKeyメソッドは静的メソッドを初めて呼び出すときに機能しますが、少数の呼び出しの後に、辞書は前の呼び出しで働いたのと同じキーを持つ呼び出しに対してSIGABRT例外をスローします。何か案は?Objective-C静的フィールドの問題
static NSDictionary *dictionary = nil;
static NSLock *dictionaryLock;
@implementation ApplicationSettingsHelper
+ (void) initialize
{
dictionaryLock = [[NSLock alloc] init];
// Read plist from application bundle.
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Xxxx.plist"];
dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];
// dump the contents of the dictionary to the console.
for(id key in dictionary)
{
NSLog(@"bundle: key=%@, value=%@", key, [dictionary objectForKey:key]);
}
}
+ (NSDictionary *)dictionaryItems
{
[dictionaryLock lock];
if (dictionary == nil)
{
[self initialize];
}
[dictionaryLock unlock];
return dictionary;
}
+(id)getSettingForKey:(NSString *)key
{
return [[self dictionaryItems] objectForKey:key];
}
@end
モシェ - 私はあなたの提案を取り、代わりにNSUserDefaultsを使用するように更新しました:
+ (void)load
{
// Load the default values for the user defaults
NSString* pathToUserDefaultsValues = [[NSBundle mainBundle]
pathForResource:@"Xxxx"
ofType:@"plist"];
NSDictionary* userDefaultsValues = [NSDictionary dictionaryWithContentsOfFile:pathToUserDefaultsValues];
// Set them in the standard user defaults
[[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsValues];
}
+ (id)getSettingForKey:(NSString *)key
{
return [[NSUserDefaults standardUserDefaults] valueForKey:key];
}
NSUserDefaultsというクラスがあります。これは、あなたが望むことを達成する可能性が高いでしょう。 – Moshe
はい、私はユーザーアプリケーションの設定にNSUserDefaultsを使用します。いくつかの設定URLと非ユーザ設定を読むために、plistファイルからそれらの設定を読みたいだけです。 – mservidio