代码之家  ›  专栏  ›  技术社区  ›  David Skrundz

nsarray writetofile返回“已弃用”-iPhone SDK

  •  2
  • David Skrundz  · 技术社区  · 14 年前

    我正在尝试在应用程序关闭时将一些设置保存到plist文件中,然后在应用程序启动时加载这些设置。我在一个名为数组的数组中保存了4个数字。加载工作正常,因为如果我更改了文件,应用程序将以更改文件的方式启动。

    此代码工作正常:

    - (void)LoadSettings {
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *finalPath = [path stringByAppendingPathComponent:kSaveFileLocation];
    NSArray *array = [[NSArray alloc] initWithContentsOfFile:finalPath];
    clockFaceImageSlider.value = [[array objectAtIndex:0] integerValue];
    HourTypeSwitch.on = [[array objectAtIndex:1] integerValue];
    touchRotationSwitch.on = [[array objectAtIndex:2] integerValue];
    accelerometerRotationSwitch.on = [[array objectAtIndex:3] integerValue];
    }
    

    此代码一直到保存行:

    - (void)SaveSettings {
        NSString *path = [[NSBundle mainBundle] bundlePath];
        NSString *finalPath = [path stringByAppendingPathComponent:kSaveFileLocation];
        NSArray *array = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:clockFaceImageSlider.value], [NSNumber numberWithInt:HourTypeSwitch.on], [NSNumber numberWithInt:touchRotationSwitch.on], [NSNumber numberWithInt:accelerometerRotationSwitch.on], nil];
    
        if (![array writeToFile:finalPath atomically:YES]) {
            NSLog(@"error");
        }
        //The log does print error
    }
    

    有人知道我怎样才能把它保存到困境中吗?

    谢谢

    2 回复  |  直到 14 年前
        1
  •  2
  •   Yuji    14 年前

    而不是采取 description (这是一个 NSString 一个 NSArray 把它写进一个文件,只要用 writeToFile:atomically 属于 不可变数组 本身,如

    [array writeToFile:finalPath atomically:YES];
    

    原因 writeToFile:atomically: 一个 非字符串 已弃用是因为它不能正确解释字符编码。谁让你用的 描述 ?那个人/书应该受到惩罚…

    也就是说,如果您只想保存一些条目,那么只需使用它就更容易了 NSUserDefaults here . 那么你所要做的就是

    [[NSUserDefaults standardUserDefaults] setObject: ... forKey:@"..."]
    

    框架做了所有的事情,从准备幕后的plist路径到将其保存到磁盘。

        2
  •  4
  •   nacho4d    14 年前

    不要写数组的描述nsstring,只需写数组:

    [array writeToFile:finalPath atomically:YES];
    

    或者如果需要字符串,则应使用en编码类型

    NSError *error;
    [[array description] writeToFile:finalPath atomically:YES encoding:NSUTF8StringEncodingerror:&error];
    

    但这不会写一个plist。