[英]Can I read just the key from plist?
Can I read just the key from plist without its value, also if I know the value can I read the key?我可以只从 plist 中读取没有值的键吗?如果我知道值,我可以读取键吗?
Reading.plist:阅读.plist:
NSString *path = [[NSBundle mainBundle] pathForResource:@"myPlist" ofType:@"plist"];
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
Getting all keys and all values:获取所有键和所有值:
NSArray* allmyKeys = [myDictionary allKeys];
NSArray* allmyValues= [myDictionary allValues];
Getting all keys for an values object:获取值 object 的所有键:
NSArray* allmyKeys = [myDictionary allKeysForObject:myValueObject];
As an alternative, you can use allKeysForObject:
method which returns,作为替代方案,您可以使用
allKeysForObject:
方法返回,
A new array containing the keys corresponding to all occurrences of anObject in the dictionary.
一个新数组,包含对应于字典中所有出现的 anObject 的键。 If no object matching anObject is found, returns an empty array.
如果没有找到匹配 anObject 的 object,则返回一个空数组。
From that array you can get the key by invoking the objectAtIndex:
method.从该数组中,您可以通过调用
objectAtIndex:
方法来获取密钥。
In order to read the values at app's installed folder:为了读取应用程序安装文件夹中的值:
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's method has not worked for me, then I tried this method. Jhaliya的方法对我不起作用,然后我尝试了这种方法。
Use -[NSDictionary allKeysForObject:]
*.使用
-[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;
}
*Dunno why it returns an NSArray object instead of an NSSet object, because keys are not ordered. *不知道为什么它返回一个 NSArray object 而不是一个 NSSet object,因为键没有排序。 Oh well.
那好吧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.