Can I read just the key from plist?
Asked Answered
S

4

5

Can I read just the key from plist without its value, also if I know the value can I read the key ?

Seismism answered 4/6, 2011 at 11:32 Comment(2)
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 happenSeismism
C
11

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];
Chronoscope answered 4/6, 2011 at 12:8 Comment(1)
myDictionary should really be an NSDictionary here, not an NSMutableDictionary.Devol
M
3

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.

Messapian answered 4/6, 2011 at 11:52 Comment(0)
K
1

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.

Kylie answered 4/6, 2011 at 11:39 Comment(1)
I have added an example. I didn't know about that method :)Kylie
W
1

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.

Westfalen answered 4/7, 2013 at 23:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.