gpt4 book ai didi

ios - 在第一次应用程序加载时从 Preference Bundle 初始化 IOS Preferences

转载 作者:行者123 更新时间:2023-11-28 22:08:47 33 4
gpt4 key购买 nike

在我的 AppDelegate.m 中,如果用户还没有进入设置面板,我会尝试从我的 Preference Bundle 中初始化默认值。初始化运行,我看到了符合我偏好的正确数量的对象,但它们都是空的,没有任何设置。

+ (void)initialize {
NSLog(@"Running settings initialization");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *settingsBundle =
[[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
NSDictionary *settings =
[NSDictionary dictionaryWithContentsOfFile:
[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];

NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister =
[[NSMutableDictionary alloc] initWithCapacity:[preferences count]];

[defaults registerDefaults:defaultsToRegister];
[defaults synchronize];

}

最佳答案

您正在注册一个空字典。

使用:

+ (void)initialize
{
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
[defs synchronize];

NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];

if(!settingsBundle)
{
NSLog(@"Could not find Settings.bundle");
return;
}

NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];

for (NSDictionary *prefSpecification in preferences)
{
NSString *key = [prefSpecification objectForKey:@"Key"];
if (key)
{
// Check if value is registered or not in userDefaults
id currentObject = [defs objectForKey:key];
if (currentObject == nil)
{
// Not registered: set value from Settings.bundle
id objectToSet = [prefSpecification objectForKey:@"DefaultValue"];
[defaultsToRegister setObject:objectToSet forKey:key];
NSLog(@"Setting object %@ for key %@", objectToSet, key);
}
else
{
// Already registered
NSLog(@"Key %@ is already registered with Value: %@).", key, currentObject);
}
}
}

[defs registerDefaults:defaultsToRegister];
[defaultsToRegister release];
[defs synchronize];
}

关于ios - 在第一次应用程序加载时从 Preference Bundle 初始化 IOS Preferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23379785/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com