[英]Copy plist to documents directory and read from it
我在AppDelegate中的didFinishLaunchingWithOptions时将plist复制到文档目录,如下所示:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self performSelector:@selector(copyPlist)];
return YES;
}
- (void)copyPlist {
NSFileManager *fileManger=[NSFileManager defaultManager];
NSError *error;
NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];
NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:@"Obj.plist"];
if ([fileManger fileExistsAtPath:destinationPath]){
NSLog(@"database localtion %@",destinationPath);
return;
}
NSString *sourcePath=[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"Obj.plist"];
[fileManger copyItemAtPath:sourcePath toPath:destinationPath error:&error];
}
然后,我试图在我的视图中显示plist的内容,如下所示:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Obj.plist"];
NSLog(@"plist path %@", path);
sortedObj = [[NSMutableArray alloc]initWithContentsOfFile:path];
NSLog(@"objects %@", sortedObj);
日志结果:
数据库本地化:
/Users/kdb/Library/Application Support/iPhone Simulator/5.1/Applications/4E165740-01CD-4ED3-8971-FDCCB1751DD1/Documents/Obj.plist
plist路径:
与数据库位置相同
对象:
(空值)
内容为空。 如何使其运作?
plist是带有字典的数组。
您是否尝试过NSLog捆绑软件中资源的路径? 看起来正确吗? 除此之外,我认为您应该使用其他方法定位它:
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension
因此,您的方法调用将是:
NSString *sourcePAth = [[NSBundle mainBundle] pathForResource:@"Obj" ofType:@"plist"];
然后,我认为您无法执行[[NSMutableArray alloc] initWithContentsOfFile:path];
。 而是尝试使用NSDictionary:
NSDictionary *loadedPlist = [[NSDictionary alloc] initWithContentsOfFile:pathString];
//and then, if you need to edit it:
NSMutableDictionary *workingCopy = [loadedPlist mutableCopy];
只需阅读您对问题的编辑即可。 plists不能视为数组,它们始终是字典,因此必须使用NSDictionary反序列化。
我不知道为什么它只有在没有日志的情况下才第一次起作用。 你可以张贴吗? 同样,即使您似乎可以使用NSMutableArray进行操作,但如果坚持使用NSDisctionary反序列化样式,则调试该问题也将更加容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.