我正在使用我之前使用的一段代码成功将plist加载到数组中:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
initWithContentsOf文件失败(数组为空,表明它无法在应用程序包中找到plist)。
在iPhone模拟器下,我检查了第一行创建的路径指向app文件(确实如此),并使用Finder上下文菜单“Show package contants”向自己证明“species_name.plist”实际上是在捆绑中 - 长度表明它包含东西,所以它应该工作(并且在我编写的其他iOS应用程序中)。建议最受欢迎......
[env Xcode 4.2 beta,iOS 4.3.2]。
答案 0 :(得分:27)
您应该使用initWithContentsOfFile:
实例的NSDictionary
方法,而不是NSArray
。
这是样本:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
NSArray *array = [NSArray arrayWithArray:[dict objectForKey:@"Root"]];
或者这个:
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];
NSArray *array = [NSArray arrayWithArray:[temp objectForKey:@"Root"]];
的修改
您可以使用initWithContentsOfFile:
的{{1}}方法,使用NSArray
方法[{1}}创建的文件。使用writeToFile:atomically:
创建的Plist具有以下结构:
NSArray
在XCode中创建的Plist有这样的结构:
writeToFile:atomically:
这就是为什么<plist version="1.0">
<array>
...Content...
</array>
</plist>
dosnt的<plist version="1.0">
<dict>
...Content...
</dict>
</plist>
方法有效。
答案 1 :(得分:3)
plist
:
OR(基本上两者都相同)
可以这样读:
NSString *file = [[NSBundle mainBundle] pathForResource:@"appFeatures" ofType:@"plist"];
NSArray *_arrFeats = [NSArray arrayWithContentsOfFile:file];
NSLog(@"%d", _arrFeats.count);
其中appFeatures
是plist
的名称。
(iOS 6.1)
答案 2 :(得分:0)
试试这个简单的方法:
- (void)viewDidLoad
{
[super viewDidLoad];
[self plistData];
}
- (void)plistData
{
NSString *file = [[NSBundle mainBundle] pathForResource:@"appFeatures" ofType:@"plist"];
NSArray *messages = [NSArray arrayWithContentsOfFile:file];
NSLog(@"%d", messages.count);
for (int i=0; i<messages.count; i++)
{
NSString *data = [messages objectAtIndex:i];
NSLog(@"\n Data = %@",data);
}
}