2009-09-11 95 views
0

不知道爲什麼我的.plist看起來像這樣,當viwed作爲源代碼,而不是像XML文件。從plist返回項目數

{ 

    authorLastName = Doe; 
    authorFirstName = Jane; 
    imageFilePath = "NoImage.png"; 
    title = "Account Test 1"; 
    year = 2009; 
}, 

{ 

    authorLastName = Doe; 
    authorFirstName = John; 
    imageFilePath = "NoImage.png"; 
    title = "Account Test 2"; 
    year = 2009; 
} 

是對的.plist應該作爲源代碼查看時的樣子嗎?

第二,任何人都可以舉一個例子來說明如何重新計算每個字典中的最後一個項目的數量嗎?我已經研究過這麼多個小時了,我把我的頭髮拉出來,因爲我無法繼續前進,直到我得到正確的答案!我嘗試的每種方法都返回0.我在iPhone編程方面真的很新,所以我希望能得到任何幫助!也許是閱讀plist的完整例子嗎?

回答

1

.plist文件可以採用兩種形式,XML或文本。你擁有的是文本形式,並且在概念上更容易理解,而XML格式是...以及我確信有一些優勢(這是創建plist時的默認值,不知道爲什麼你不是' T)。

我不確定你的計數問題是什麼。您是否要求查找有多少項目(2)或這些項目中有多少項具有姓氏屬性集(本例中爲2個)或總共有多少項(10)?

在任何情況下,你會開始了這樣的

NSArray *arr = [NSArray arrayWithContentsOfFile:pathToFile]; 
//Make sure arr is not nil at this point. If it is, there's either a formatting issue with the file, or the file couldn't be found based on the path you gave 

然後,如果你試圖在第一種情況:

int count = arr.count; 

或者第二種情況:

int count = 0; 
for (NSDictionary *dict in arr) { 
    NSString *lastName = [dict objectForKey:@"authorLastName"]; 
    if (lastName) { 
     ++count; 
    } 
} 

或第三種情況:

int count = 0; 
for (NSDictionary *dict in arr) { 
    count += dict.count; 
} 
+0

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString * documentsDirectory = [paths objectAtIndex:0]; 的NSString * myPlistPath = [documentsDirectory \t \t \t \t \t \t stringByAppendingPathComponent:@ 「Accounts.plist」]; NSArray * arr = [NSArray arrayWithContentsOfFile:myPlistPath]; int count = 0; (NSDictionary * dict in arr){ \t count + = dict.count; } return count; ////////////////////////// 上述線端模擬器,錯誤: 程序接收到的信號:「EXC_BAD_ACCESS」。 – WrightsCS 2009-09-11 04:46:55

0

我Finnaly得到了plist計數工作!

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *myPlistPath = [documentsDirectory 
         stringByAppendingPathComponent:@"Accounts.plist"]; 

NSArray *arr = [NSArray arrayWithContentsOfFile:myPlistPath]; 

int count = 0; 
for (NSDictionary *dict in arr) { 
    NSString *lastName = [dict objectForKey:@"authorLastName"]; 
    if (lastName) { 
     ++count; 
    } 
} 
return([NSString stringWithFormat:@"%d Accounts", count]);