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

一世执手 提交于 2019-11-28 12:59:26

问题


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!



来源:https://stackoverflow.com/questions/26889507/how-to-save-an-array-to-plist-in-the-apps-mainbundle-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!