2009-09-11 92 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]);