Can I read only the key from plist?

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

+5
source share
4 answers

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 a value object:

NSArray* allmyKeys = [myDictionary  allKeysForObject:myValueObject];
+11
source

Alternatively, you can use a method allKeysForObject:that returns

A new array containing keys matching all occurrences of anObject in the dictionary. If the object matching anObject is not found, returns an empty array.

From this array you can get the key by calling the method objectAtIndex:.

+3

-[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;
}

* I don’t know why it returns an NSArray instead of an NSSet because the keys are not ordered. Oh good.

+1
source

To read the values ​​in the installed application 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];

The Jhaliya method did not work for me, then I tried this method.

+1
source

All Articles