簡體   English   中英

從Plist中的數組創建NSArray

[英]Create NSArray from Array within Plist

我有一個這樣的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>

我將此文件保存在一個名為filePath的變量中。

假設我想從plist中獲取數組1,如何從中獲取一個NSArray?

編輯:同樣,我想從plist中的特定數組創建一個數組。

當您閱讀字典時,將為您創建其中包含的數組。 您只需要通過使用適當的密鑰要求-objectForKey:來訪問它們。

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

因此,您想將此plist的內容讀入數組。 這很容易做到。 從本地包中獲取plist文件。 創建一個空數組。 在其中插入值。

// 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