【问题标题】:Not Able to write Boolean in plist file无法在 plist 文件中写入布尔值
【发布时间】:2011-07-06 08:38:01
【问题描述】:

我正在尝试将布尔值写入 plist 文件,但我真的不知道我在哪里做错了。我什至没有收到任何异常/错误,但相关文件中的值保持不变。而且文件路径也是正确的,myDict的分配表明已经从文件中读取了值。

下面是我写的代码

-(void)SetSettings:(BOOL)SoundOn: (BOOL)GlowOn
{
    NSString *pathSettingFile = [[NSString alloc]initWithString:[[NSBundle mainBundle]pathForResource:@"AppSettings" ofType:@"plist"]];

    NSMutableDictionary *myDict = [NSMutableDictionary dictionaryWithContentsOfFile:pathSettingFile];

    [myDict setObject:[NSNumber numberWithBool:SoundOn] forKey:@"isSoundOn"];
    [myDict setObject:[NSNumber numberWithBool:GlowOn] forKey:@"isGlowOn"];
    [myDict writeToFile:pathSettingFile atomically:NO];

    [myDict release];
    [pathSettingFile release];
}

【问题讨论】:

    标签: iphone objective-c xcode ios4


    【解决方案1】:

    您不能写入主包。您只能从主包中读取。如果你想写一个文件,你需要把它放到你应用的文档目录中。

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]]; 
    

    编辑:

    如果您需要主包中的 plist,您可以先将其复制到文档目录中,然后对其进行修改。

        NSError *error;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]]; 
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
        if (![fileManager fileExistsAtPath: path]){
            NSLog(@"File don't exists at path %@", path);
    
            NSString *plistPathBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
    
            [fileManager copyItemAtPath:plistPathBundle toPath: path error:&error]; 
        }else{
            NSLog(@"File exists at path:%@", path);
        }
    

    【讨论】:

    • 感谢您的回复,看起来很合乎逻辑,我已经尝试了您推荐的代码,它运行良好,但进入条件,好像文件不存在于路径上,虽然我已经将它放在那里在资源文件夹中:) 我也检查了文件名的拼写,你能帮我看看吗:)
    • 好像我不知道文档目录在哪里,或者我们只能通过代码访问它??
    • 您可以使用 nslog 来获取控制台中的路径并浏览您的 comp 以查看文件。我只能通过代码访问它。
    • 完美!! .. 我明白了:) ...我第一次以编程方式将文件从NSBundle mainBundle 复制到目录:) 非常感谢
    【解决方案2】:

    您不能写入/修改资源中的文件。它们仅用于阅读。尝试在应用程序的 documnets 目录中创建相同的(plist 文件)。

    【讨论】:

      【解决方案3】:

      [myDict writeToFile:pathSettingFile atomically:NO]; 返回什么?我认为您无法写入文件。

      this回答

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多