无法在设备上读取/写入plist,但可以在模拟器中

时间:2014-06-20 21:43:21

标签: iphone objective-c plist

我一直在关注Stackoverflow上有很多类似问题的帖子,但我仍然无法弄清楚为什么我不能写/读我的plist。 这是我将plist加载到应用程序的方法。 这应该将plist复制到设备的文档文件夹而不是 resources文件夹,对吗?

-(void)loadPlist:(NSString*)plistString {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", plistString]];

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:path]) {
    NSString *bundle = [[NSBundle mainBundle]pathForResource:plistString ofType:@"plist"];

    [fileManager copyItemAtPath:bundle toPath:path error:&error];
} else {
    NSLog(@"%@ already exists",path);
}
}

这就是我写给我的plist的方式:

-(void)writeScore:(NSString*)objectstring forPlayer:(int)playerTag {
switch (playerTag) {
    case 1:
        NSLog(@"Wrote to 1");
        holeInt = [P1hole_Label.text integerValue];
        plistpath = [[NSBundle mainBundle]pathForResource:@"Scores" ofType:@"plist"];
        plistdata = [[NSMutableDictionary alloc]initWithContentsOfFile:plistpath];
        [plistdata setObject:[NSString stringWithString:objectstring] forKey:[NSString stringWithFormat:@"Hole %i", holeInt]];
        [plistdata writeToFile:plistpath atomically:YES];
        break; 
Etc.

以下是我如何阅读plist:

-(void)createNewHoleLabel:(NSString*)plistString andSetX:(int)x {
//SetX; 0 = P1, 1 = P2 etc.

UILabel *label = [UILabel new];
[label setFrame:CGRectMake(80 + 53 * x, 93 + 26 * integer, 50, 25)];

NSString *path = [[NSBundle mainBundle]pathForResource:plistString ofType:@"plist"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithContentsOfFile:path];

label.text = [dict objectForKey:[NSString stringWithFormat:@"Hole %i", integer + 1]];

[label setAdjustsFontSizeToFitWidth:YES];
[label setTextAlignment:NSTextAlignmentCenter];
integer++;
[scrollview addSubview:label];
}

我希望你能帮助我。如有需要,请询问更多详情。

1 个答案:

答案 0 :(得分:3)

writeScore:forPlayer:

plistpath = [[NSBundle mainBundle]pathForResource:@"Scores" ofType:@"plist"];
...
[plistdata writeToFile:plistpath atomically:YES];

您正在尝试写入无法在设备上执行的应用程序包。您应该编写Documents目录。