In a new iPhone app I am currently developing I needed to be able to import the data from a plist file (apple’s XML formatted file) stored within the app bundle and display it in my app. Luckily there is a very handy class method in the NSDictionary class which enables you to create a Dictionary (basically an array with key values) from a file.
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:file];
As I wanted to be able to iterate through all the values in the plist, I created a main dictionary named “database” then within that an array which stored another dictionary that holds my key based data.
This is the code I used to open the plist file and iterate though all the values it contains:
NSString *file = [[NSBundle mainBundle] pathForResource:@"list_of_dogs" ofType:@"plist"]; NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:file]; NSArray *dogArray = [[NSArray alloc] initWithArray:[dict objectForKey:@"database"]]; for (NSDictionary *sectionDict in dogArray){ //loop through the data from the plist NSLog(@"Dog Name = %@ ",[sectionDict objectForKey:@"dog_name"]); NSLog(@"Dog Type = %@ ",[sectionDict objectForKey:@"dog_type"]); }
This is the XML format of the plist file I created:
<?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>database</key> <array> <dict> <key>dog_name</key> <string>Jasper</string> <key>dog_type</key> <string>Great Dane</string> </dict> <dict> <key>dog_name</key> <string>Samd</string> <key>dog_type</key> <string>Jack Russell</string> </dict> </array> </dict> </plist>
Any questions? hit me up in the comments