arrayWithContentsOfFile can't read plist file

funnyCoder picture funnyCoder · Jun 2, 2011 · Viewed 9.1k times · Source

i have a plist with an array that contain 2 strings see image :

http://imageshack.us/photo/my-images/263/myplist.png/

and in my viewDidLoad i add this :

NSString *file = [[NSBundle  mainBundle] pathForResource:@"Data"    ofType:@"plist"];

NSArray *array = [NSArray    arrayWithContentsOfFile:file];

NSLog(@"array = %@", array);

But i got always null why? Thanks for help.

UPDATE : the solution is that you need to manually edit the plist file (Xcode4 use Dictionnary by default)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <array>
        <string>HO</string>
        <string>HI</string>
    </array>
</array>
</plist>

Answer

omz picture omz · Jun 2, 2011

Most likely, your plist is a dictionary that contains an array (Xcode 4 doesn't allow to create plists with an array as the root object). Try something like this:

NSString *file = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:file];
NSArray *array = [dict objectForKey:@"Array"];
NSLog(@"%@", array);