How to save an array to .plist in the App's ma

2020-02-16 02:31发布

问题:

How I can save array to .plist with array type?

I try this, but is not working

    let path = NSBundle.mainBundle().pathForResource("Setting", ofType: "plist")
    let arrayWithProperties = NSArray(array: [
        NSNumber(integer: nowThemeSelected),
        NSNumber(integer: imageForBackgroundNumber),
        NSNumber(integer: imageForButtonNumber),
        NSNumber(integer: colorOfButton)])


    arrayWithProperties.writeToFile(path!, atomically: true)

回答1:

You can't write to the main bundle in iOS, everything inside your Apps bundle is read only.

[The App's bundle ] directory contains the app and all of its resources. You cannot write to this directory. To prevent tampering, the bundle directory is signed at installation time. Writing to this directory changes the signature and prevents your app from launching. You can, however, gain read-only access to any resources stored in the apps bundle.

Consider reading the file system programming guide and then persist your plist to the correct location. Preferably the Documents directory or the Library directory. Up to you.



回答2:

You can't write to the Bundle directory but you can write to the Documents directory. So, use this code!

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var path:NSString = documentsPath.stringByAppendingPathComponent("Setting.plist");

When you'll writeToFile() use this:

arrayWithProperties.writeToFile(path as String, atomically: true)

Good Luck!