plists - iOS development (NSString)



我创建了一个名为"hospitals"的plist,将第一行插入一个数组,其中包含三个项目作为字符串。

我的代码有什么问题:

NSArray *hospitals = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Hospitals" ofType:@"plist"]];
    NSString *first = [[NSString alloc] initWithFormat:@"%@", [hospitals objectAtIndex:0]];
    NSLog(@"%@",first);

这是给我(null)作为结果!

要么属性列表文件不存在(检查目标的"Copy Resources"构建阶段),有不同的名称(注意iOS的文件系统是区分大小写的),根本不是属性列表(可能有语法错误),不可读或者属性列表的根不是数组,而是字典。

如果hospitals == nil以上任何一个是问题

试试这个:

NSString *errorDesc = nil;
NSPropertyListFormat format;
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:[[NSBundle mainBundle] pathForResource:@"Hospitals" ofType:@"plist"]];
NSMutableDictionary *properties = (NSMutableDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
NSArray *hospitals = (NSArray *)[properties valueForKey:@"names"]; 
NSString *first = [hospitals objectAtIndex:0];
NSLog(@"%@",first);

最新更新