2011-08-04 172 views
0

我有一个plist,它是一个数组,文件名称叫做startups.plist。我试图用下面的代码将它读入数组中:阅读plist问题

NSString *path = [[NSBundle mainBundle] pathForResource:@"startups" ofType:@"plist"]; 
NSMutableArray * wordList = [[NSMutableArray alloc] initWithContentsOfFile:path]; 

但是,wordList在这里总是为0。印刷设备上测试时的路径,它给了我:

/var/mobile/Applications/CCBF94D9-389C-4D63-B023-F39653FDCEF4/My.app/startups.plist 

这里的结构看起来像plist中的内容:

enter image description here

数组的大小为0 什么时我在这里做错了吗?

+0

'path'的值(和内容)是什么? – fbrereto

+0

我已经把它放在正确的位置..它就是那个var/mobile/Applications/,,,, – aherlambang

回答

2

initWithContentsOfFile:不会打开plist文件。下面是一个示例:

NSString *errorDesc = nil; 
NSPropertyListFormat format; 
NSString *path = [[NSBundle mainBundle] pathForResource:@"startups" ofType:@"plist"]; 
NSData  *plistXML = [[NSFileManager defaultManager] contentsAtPath:path]; 
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization      
              propertyListFromData:plistXML 
mutabilityOption:NSPropertyListMutableContainersAndLeaves 
              format:&format 
              errorDescription:&errorDesc]; 
NSLog(@"%@",[temp objectForKey:@"Root"]); 
+0

真棒!谢谢......我正在阅读教程,他们使用initWithContentsOfFile – aherlambang

+0

不客气。如果使用'NSDictionary'的'initWithContentsOfFile'方法可能会打开它,但我更喜欢这种方法。 – VenoMKO

1

你必须使用NSDictionary,因为你的plist是一个字典其中有一个关键的根是一个数组。

NSString *path = [[NSBundle mainBundle] pathForResource:@"startups" ofType:@"plist"]; 
NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; 

NSMutableArray *wordList = (NSMutableArray *)[dict objectForKey:@"Root"]; 

我不确定铸造到NSMutableArray。也许你必须做

NSMutableArray *wordList = [NSMutableArray arrayWithArray:(NSArray*)[dict objectForKey:@"Root"]] 
+2

这是不正确的。 “根”不是字典键,它只是表示属性列表中的根对象。 – Caleb

+0

如果我试图重新这种结构的plist中的XML看起来是这样的: 一个