2012-08-23 53 views
1

我有一個屬性列表文件,用於存儲問題和答案數據。在這個文件中,我有一個數組的集合,在這些數據中我存儲了不同的類別和問題。但是我似乎無法訪問這些數據?訪問Plist數組/目標 - 目標C

屬性文件;

<?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>Category1</key> 
<array> 
    <array> 
     <string>Question1</string> 
     <string>Answer1</string> 
    </array> 
    <array> 
     <string>Question2</string> 
     <string>Answer2</string> 
    </array> 
    <array> 
     <string>Question3</string> 
     <string>Answer3</string> 
    </array> 
    <array> 
     <string>Question4</string> 
     <string>Answer4</string> 
    </array> 
</array> 
</dict> 
</plist> 

下面我使用通過使用兩個簡單的按鈕逐步訪問屬性列表文件;

-(IBAction)nextleft { 
    [self bingsound]; 
    if (questionCounter > 1) { 
     questionCounter -= 1; 
    } 
    [self nextQuestion]; 
} 

-(IBAction)nextright { 
    [self bingsound]; 
    if (questionCounter < 20) { 
     questionCounter += 1; 
    } 
    [self nextQuestion]; 
} 

-(void)nextQuestion { 
    NSArray *pair; 
    pair = [categories objectAtIndex:questionCounter]; 
    plistQuestion = [pair objectAtIndex:0]; 
    plistAnswer = [pair objectAtIndex:1]; 
    abbreviation.text = plistQuestion; 
} 

我正在填充類別數組,如下所示;

categories = [NSArray arrayWithContentsOfFile:@"questions.plist"]; 
+0

你能在文本編輯器中打開你的屬性列表,並張貼開場白嗎?該截圖看起來不正確,第一項應稱爲「根」,通常不能通過plist編輯器進行編輯。你有一個無效的屬性列表或字典作爲根對象 - 在調試器中,檢查你的類別數組是否被初始化爲。 – jrturton

+0

剛纔補充說,現在讓你看看。 – Kolors

回答

1

您的屬性列表有一個字典作爲根對象,而不是一個數組。

拆下頂部這些行:

<dict> 
<key>Category1</key> 

而此行的末尾:

</dict> 

此外,關注@繆拉的意見,並得出一個正確的路徑到你的文件,而不是一個普通的串。

一般來說,在這樣的問題下,調試器是你的朋友。在你的方法中加入一個斷點,然後檢查每個階段(派生路徑,提取數組),得出你要輸出的值。

+0

感謝您的幫助,簡單的修復,因爲我懷疑和熨平了一些問題後,它工作的一種享受。謝謝! – Kolors

+1

你應該問一個單獨的問題。 – jrturton

1

您應該爲arrayWithContentsOfFile:提供plist文件的完整路徑。以下應該工作:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"questions" ofType:@"plist"]; 
categories = [NSArray arrayWithContentsOfFile:filePath]; 
+0

感謝您的幫助! – Kolors