iphone - 无法在 plist 文件中写入 bool 值

标签 iphone objective-c xcode ios4

我正在尝试将 bool 值写入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];
}

最佳答案

您无法写入主包。您只能从主包中读取。如果您想编写文件,则需要将其放入应用程序的文档目录中。

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

关于iphone - 无法在 plist 文件中写入 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6593627/

相关文章:

iphone - 让网站用户知道有可用的 iOS 应用程序

ios - [[self.effectsTableView cellForRowAtIndexPath :indexPath]. textLabel text] 在 didSelectRowAtIndexPath 上返回 nil

objective-c - 从 php 返回两个字符串到 ios

ios - 将用户位置传递给MKMapItem

iphone - viewController 中的 pushViewController 和 tableViewController

android - 使用移动应用程序保护通信 [真实性、隐私和完整性]?

iphone - 何时正确释放对象

ios - setNeedsStatusBarAppearanceUpdate 使我的应用程序崩溃

iphone - 如何减小 iPhone View 中日期选择器控件的大小

ios - swift 函数的默认返回类型是什么?