Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray initWithContentsOfFile returns nil

I'm trying to read a plist file into NSArray using initWithContentsOfFile as described here

My code looks like this

    NSBundle *bundle = [NSBundle mainBundle];
    NSString *plistPath = [bundle pathForResource:
                           @"routes" ofType:@"plist" ];
    routes = [[NSArray alloc] initWithContentsOfFile:plistPath ];
    NSLog:(@"contents of myArray %@", routes);

routes.plist has a perfectly simple structure of array and 2 string values inside

<?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">
<dict>
    <key>Root</key>
    <array>
        <string>1</string>
        <string>2</string>
    </array>
</dict>
</plist>

This is how it looks in xcode

Everything seems to be fine. plistPath initializes with correct value, which means file is copied to the bundle and can be readed. But routes = [[NSArray alloc] initWithContentsOfFile:plistPath ]; returns 0x0 value. I think this is equal to nil

What is wrong with my code?


2 Answers

Actually your plist is a dictionary.

Change this:

<dict>
    <key>Root</key>
    <array>
        <string>1</string>
        <string>2</string>
    </array>
</dict>

to this:

<array>
    <string>1</string>
    <string>2</string>
</array>
like image 94
calimarkus Avatar answered Sep 20 '26 17:09

calimarkus


I think you want to do something like this:

NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:
                       @"routes" ofType:@"plist"];

NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
NSArray *routes = [dictionary objectForKey:@"Root"];
like image 33
mservidio Avatar answered Sep 20 '26 17:09

mservidio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!