Can I read just the key from plist without its value, also if I know the value can I read the key ?
Can I read just the key from plist?
What if different keys have the same value? What must happen then? –
Kylie
@WTP: No Keys have the same value and the case will not happen –
Seismism
Reading .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:
NSArray* allmyKeys = [myDictionary allKeysForObject:myValueObject];
myDictionary
should really be an NSDictionary
here, not an NSMutableDictionary
. –
Devol As an alternative, you can use allKeysForObject:
method which returns,
A new array containing the keys corresponding to all occurrences of anObject in the dictionary. If no object matching anObject is found, returns an empty array.
From that array you can get the key by invoking the objectAtIndex:
method.
Use -[NSDictionary allKeysForObject:]
*.
Example
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. Oh well.
I have added an example. I didn't know about that method :) –
Kylie
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.
© 2022 - 2024 — McMap. All rights reserved.