【问题标题】:iphone : Settings.bundle returns null valueiphone:Settings.bundle 返回空值
【发布时间】:2012-09-25 09:03:25
【问题描述】:

我使用的是 xCode 3.2,然后移至 xCode 4.2 并从 Settings.bundle 获取一些值......它工作正常。

虽然我需要编辑 Settings.bundle 中的一些值,但 Root.plist 文件没有显示,所以我按照以下步骤操作,但没有对文件进行任何更改。

1) Click on the Settings.Bundle file, go over to the utilities window,
and look in the File Inspector.
2) Using the drop-down, change the file type to 'Application Bundle'

之后我可以看到 Root.plist 但现在无法在应用程序中获取它的值。实际上得到 Null 而不是 value。

下面是Settings.bundle的代码和图片

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
host = [defaults stringForKey:@"meter_preference"];
if(host == nil)
{
    host = @"10.20.20.1";
    DDLogError(@"Meter host is nil from NSUserDefaults, defaulting to %@", host);
}

【问题讨论】:

    标签: iphone objective-c ios xcode ipad


    【解决方案1】:

    从你的代码中,试试这个想法..

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        host = [defaults stringForKey:@"meter_preference"];
        if(!host == nil)
        {
            host = @"10.20.20.1";
            DDLogError(@"Meter host is nil from NSUserDefaults, defaulting to %@", host);
        }
    

    查看此链接可能会对您有所帮助...

    iPhone - reading Setting.bundle returns wrong values

    NSUserDefaults Settings Bundle Plist

    【讨论】:

      【解决方案2】:

      我得到了解决方案,只需在 applicationDidFinishLaunchingWithOptions 中调用以下代码来初始化用户默认值。它有效

      将第一行中的somePropertyYouExpect 替换为您存储在用户默认值中的属性。

      if (![[NSUserDefaults standardUserDefaults] objectForKey:@"somePropertyYouExpect"])  {
      
          NSString  *mainBundlePath = [[NSBundle mainBundle] bundlePath];
          NSString  *settingsPropertyListPath = [mainBundlePath
                                                 stringByAppendingPathComponent:@"Settings.bundle/Root.plist"];
      
          NSDictionary *settingsPropertyList = [NSDictionary 
                                                dictionaryWithContentsOfFile:settingsPropertyListPath];
      
          NSMutableArray      *preferenceArray = [settingsPropertyList objectForKey:@"PreferenceSpecifiers"];
          NSMutableDictionary *registerableDictionary = [NSMutableDictionary dictionary];
      
          for (int i = 0; i < [preferenceArray count]; i++)  { 
              NSString  *key = [[preferenceArray objectAtIndex:i] objectForKey:@"Key"];
      
              if (key)  {
                  id  value = [[preferenceArray objectAtIndex:i] objectForKey:@"DefaultValue"];
                  [registerableDictionary setObject:value forKey:key];
              }
          }
      
          [[NSUserDefaults standardUserDefaults] registerDefaults:registerableDictionary]; 
          [[NSUserDefaults standardUserDefaults] synchronize]; 
      } 
      

      【讨论】:

      • XCode 6.3 存在同样的问题,但您的解决方案仍然有效。
      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 2021-12-21
      • 2015-11-07
      • 2020-05-20
      • 2020-11-08
      • 2013-10-09
      • 2012-03-29
      • 2019-11-24
      相关资源
      最近更新 更多