Search code examples
iosobjective-cplist

Objective-C Access Specific Item in Plist


I have created an app, and I am trying to access a URL that is stored in a plist file. At this state I am just trying to log the contents out. I am aware similar questions have been asked before, but I am asking specifically to my scenario how to I access Item 0. I am trying to access Item 0 inside InternalViaSafari this manifests itself inside the URLValidator and then that inside the Root. The code I have so far is: plist file

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"plist-file-name" ofType:@"plist"];
NSDictionary* plist = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSString* name = [plist valueForKeyPath:@"URLValidator.InternalViaSafari"];
NSLog(name);

Solution

  • You cannot use keyPath like that for this as far as I know. InternalViaSafari is not a property of URLValidator dictionary. What's more InternalViaSafari is an Array not a String in your plist.

    In order to get this string you'd need something like this :

    NSArray *internalViaSafari = plist[@"URLValidator"][@"InternalViaSafari"];
    NSString *name = internalViaSafari.firstObject;
    

    What happens here, is that you get the value under the URLValidator key from your plist dictionary. This value is also a Dictionary (this can be clearly seen in the plist screenshot you shared), so you get the value under the InternalViaSafari key. This value is in turn an Array, which has Strings as its elements. In this example I extracted the first entry from this array.