1

当 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 是一个带有字典的数组。

4

1 回答 1

0

您是否尝试过 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];

只需阅读您对问题的编辑。plist 不能被视为数组,它们始终是字典,因此必须使用 NSDictionary 反序列化。

我不知道为什么它只在没有日志的情况下第一次工作。你能把它们贴出来吗?此外,即使它似乎使用 NSMutableArray 工作,如果您坚持反序列化的 NSDisctionary 样式,调试问题会更容易。

于 2012-08-11T18:40:40.777 回答