【问题标题】:Can I read just the key from plist?我可以从 plist 中读取密钥吗?
【发布时间】:2011-06-04 11:32:25
【问题描述】:

我可以只从 plist 中读取没有值的键吗?如果我知道值,我可以读取键吗?

【问题讨论】:

  • 如果不同的键有相同的值怎么办?那么必须发生什么?
  • @WTP: 没有Keys具有相同的值,这种情况不会发生

标签: ios iphone ipad plist key-value


【解决方案1】:

阅读.plist:

NSString *path = [[NSBundle mainBundle] pathForResource:@"myPlist" ofType:@"plist"];    
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

获取所有键和所有值:

NSArray* allmyKeys = [myDictionary  allKeys];
NSArray* allmyValues= [myDictionary  allValues];

获取值对象的所有键:

NSArray* allmyKeys = [myDictionary  allKeysForObject:myValueObject];

【讨论】:

  • myDictionary 应该是NSDictionary,而不是NSMutableDictionary
【解决方案2】:

作为替代方案,您可以使用返回的allKeysForObject: 方法,

一个新数组,其中包含对应于字典中所有出现的 anObject 的键。如果没有找到匹配 anObject 的对象,则返回一个空数组。

您可以通过调用objectAtIndex: 方法从该数组中获取

【讨论】:

    【解决方案3】:

    使用-[NSDictionary allKeysForObject:]*。


    示例

    NSArray *keys = [myDict allKeysForObject:@"My Value"];
    if ([keys count] != 0) { // to prevent out-of-bounds crashes
      NSString *key = [keys objectAtIndex:0];
      return key;
    } else {
      return nil;
    }
    

    *不知道为什么它返回一个 NSArray 对象而不是一个 NSSet 对象,因为键没有排序。哦,好吧。

    【讨论】:

    • 我添加了一个例子。我不知道那种方法:)
    【解决方案4】:

    为了读取应用程序安装文件夹中的值:

     NSString *PListName=@"ExamplePlist";
     NSString *_PlistNameWithExtension=[NSString stringWithFormat:@"%@.plist",PlistName];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
    NSString *documentsDirectory = [paths objectAtIndex:0]; //2
    NSString *path = [documentsDirectory stringByAppendingPathComponent:_PlistNameWithExtension]; //3
    
    NSDictionary *myDictionary = [[NSDictionary alloc] initWithContentsOfFile:path];
    NSLog(@"%@",[myDictionary description]); 
    NSArray *AllKeys=[myDictionary allKeys];
    

    Jhaliya 的方法对我不起作用,然后我尝试了这种方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-09
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      相关资源
      最近更新 更多