我創建了一個從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