Objective c 访问应用程序包中的plist返回null
我正在使用一段我以前成功使用过的代码将plist加载到数组中:Objective c 访问应用程序包中的plist返回null,objective-c,ios,plist,nsbundle,Objective C,Ios,Plist,Nsbundle,我正在使用一段我以前成功使用过的代码将plist加载到数组中: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"]; NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath]; initWithContentsOf文件失败(数组为null,表明它在应用程序包中找不到plist) 在iP
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
initWithContentsOf文件失败(数组为null,表明它在应用程序包中找不到plist)
在iPhone模拟器下,我检查了第一行创建的路径是否指向应用程序文件(确实如此),并使用Finder上下文菜单“Show package contants”向自己证明“species_name.plist”实际上在捆绑包中——长度表明它包含内容,所以应该可以工作(并且在我编写的其他iOS应用程序中也有)。建议非常受欢迎
[env Xcode 4.2 beta版,iOS 4.3.2]。您应该使用
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:
NSArray的方法method
与使用writeToFile:atomically:
methodNSArray
。使用writeToFile:atomically:
创建的Plist具有以下结构:<plist version="1.0">
<array>
...Content...
</array>
</plist>
…内容。。。
在XCode中创建的Plist具有以下结构:
<plist version="1.0">
<dict>
...Content...
</dict>
</plist>
…内容。。。
这就是为什么
initWithContentsOfFile:
NSArray的方法dosnt起作用。plist
这种类型:
或者(两者基本相同)
可以这样理解:
NSString *file = [[NSBundle mainBundle] pathForResource:@"appFeatures" ofType:@"plist"];
NSArray *_arrFeats = [NSArray arrayWithContentsOfFile:file];
NSLog(@"%d", _arrFeats.count);
其中appFeatures
是plist
的名称。
(iOS 6.1)尝试以下简单方法:
- (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);
}
}
-(void)viewDidLoad
{
[超级视图下载];
[自身数据];
}
-(无效)plistData
{
NSString*文件=[[NSBundle mainBundle]路径资源:@“plist”类型的“appFeatures”;
NSArray*消息=[NSArray arrayWithContentsOfFile:file];
NSLog(@“%d”,messages.count);
对于(int i=0;i