Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Load dictionaries from plist file to an array

I'm trying to load the following plist file to a NSMutableArray

<?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>Item 0</key>
<dict>
    <key>title</key>
    <string>East Coast</string>
</dict>
<key>Item 1</key>
<dict>
    <key>title</key>
    <string>West Coast</string>
</dict>
<key>Item 2</key>
<dict>
    <key>title</key>
    <string>South Rhodes</string>
</dict>
</dict>
</plist>

I'm using the following Objective C code

- (void)viewDidLoad 
{
    [super viewDidLoad];
    // Load data from the plist file
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Menu" ofType:@"plist"];
    self.menuArray = [NSMutableArray arrayWithContentsOfFile:plistPath];
}

The name of the plist is Menu.plist.

After the code is executed the menuArray is empty.

The strange thing is that the same code is used in Apple's "QuickContacts" Sample Code and everything works perfectly fine there.

Thank you for your time.

like image 229
George Lydakis Avatar asked Dec 12 '22 00:12

George Lydakis


1 Answers

Your plist file defines a dictionary; indeed, its root object is a dict:

<plist version="1.0">
<dict>

so to load it into some data structure, you might as well try with a NSDictionary:

self.menuDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];

Alternatively, you could change your plist so that it defines a dictionary. This is not easy to do if you use Xcode plist editor, otherwise you have a bit of text editing in front of you.

like image 183
sergio Avatar answered Jan 12 '23 18:01

sergio