简体   繁体   English

从Plist中的数组创建NSArray

[英]Create NSArray from Array within Plist

I have a plist structured like this: 我有一个这样的plist结构:

<?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. 我将此文件保存在一个名为filePath的变量中。

Let's say I wanted to take array 1 from the plist, How could I make an NSArray from this? 假设我想从plist中获取数组1,如何从中获取一个NSArray?

Edit: Again, I want to create an array from a specific array within the plist. 编辑:同样,我想从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. 您只需要通过使用适当的密钥要求-objectForKey:来访问它们。

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. 因此,您想将此plist的内容读入数组。 It's easy to do this. 这很容易做到。 Get the plist file from your local bundle. 从本地包中获取plist文件。 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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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