繁体   English   中英

我可以从 plist 中读取密钥吗?

[英]Can I read just the key from plist?

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

阅读.plist:

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

获取所有键和所有值:

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

获取值 object 的所有键:

NSArray* allmyKeys = [myDictionary  allKeysForObject:myValueObject];

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

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

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

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

 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的方法对我不起作用,然后我尝试了这种方法。

使用-[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 object 而不是一个 NSSet object,因为键没有排序。 那好吧。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM