简体   繁体   中英

Create NSArray from Array within Plist

I have a plist structured like this:

<?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>1</key>
<array>
    <string>George Washington</string>
    <string>February 22, 1732 – December 14, 1799</string>
    <string>Westmoreland, Virginia</string>
    <string>April 30, 1789 – March 4, 1797</string>
    <string>Non-partisan</string>
</array>
<key>2</key>
<array>
    <string>John Adams</string>
    <string>October 30, 1735 – July 4, 1826</string>
    <string>Braintree, Massachusetts</string>
    <string>March 4, 1797 – March 4, 1801</string>
    <string>Federalist</string>
</array>
<key>3</key>
<array>
    <string>Thomas Jefferson</string>
    <string>April 13, 1743 – July 4, 1826</string>
    <string>Shadwell, Virginia</string>
    <string>March 4, 1801 – March 4, 1809</string>
    <string>Democratic-Republican</string>
</array>
</dict>
</plist>

And I have this file in aa variable called filePath.

Let's say I wanted to take array 1 from the plist, How could I make an NSArray from this?

Edit: Again, I want to create an array from a specific array within the plist.

When you read in the dictionary, the arrays it contains are created for you. You merely need to access them by asking for the -objectForKey: using the appropriate key.

NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSArray *georgeWashingtonInfo = [dictionary objectForKey:@"1"];
NSArray *johnAdamsInfo = [dictionary objectForKey:@"2"];
NSArray *thomasJeffersonInfo = [dictionary objectForKey:@"3"];

So you want to read the content of this plist into an array. It's easy to do this. Get the plist file from your local bundle. create a empty array. insert values in that.

// Path to the plist (in the application bundle)
NSString *path = [[NSBundle mainBundle] pathForResource:
    @"DrinkArray" ofType:@"plist"];

NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:path];

// Show the values  
for (id key in dictionary) 
{
    if(key == 1) //gives array1
        NSLog(@"bundle: key=%@, value=%@", key, [dictionary objectForKey:key]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM