简体   繁体   English

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

[英]Cannot read/write from/to plist on device, but can in simulator

i've been looking at a lot of posts with a similar problem here on Stackoverflow, but i still cannot figure out why i can't write/read my plist. 我一直在关注Stackoverflow上有很多类似问题的帖子,但我仍然无法弄清楚为什么我不能写/读我的plist。 Here is my method to load my plist into the app. 这是我将plist加载到应用程序的方法。 This should copy the plist to the device's documents folder and not resources folder , correct? 这应该将plist复制到设备的文档文件夹而不是资源文件夹 ,对吗?

-(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);
}
}

This is how i write to my plist: 这是我写给我的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.

And here is how i read the plist: 以下是我如何读取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];
}

I hope you can help me. 我希望你能帮助我。 Please ask for further details if needed. 如有需要,请询问更多详情。

In writeScore:forPlayer: writeScore:forPlayer:

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

You are trying to write to the the App's bundle which can not be done on the device. 您正在尝试写入无法在设备上完成的应用程序包。 You should be writing the the Documents directory. 您应该编写Documents目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM