簡體   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