0

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)
Daniel Galasko
  • 23,617
  • 8
  • 77
  • 97

2 Answers2

5

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.

Daniel Galasko
  • 23,617
  • 8
  • 77
  • 97
  • @TheParamagneticCroissant thank you very much sir! Was quite an aggressive down vote there – Daniel Galasko Nov 12 '14 at 14:44
  • The answer was originally one sentence and didn't answer the posted question "How I can save array to .plist with array type?". – Ian MacDonald Nov 12 '14 at 14:45
  • @IanMacDonald my apologies sir, updated since to reflect more – Daniel Galasko Nov 12 '14 at 14:51
  • that programming guide sucks big time, the original question tag is swift not objc. – μολὼν.λαβέ Apr 02 '15 at 14:30
  • @GAlexander unfortunately Objective-C isn't going away anytime soon but I don't see how it makes a difference what language the guide was written in? That guide is pretty rock solid though don't see where the hate comes from? – Daniel Galasko Apr 02 '15 at 14:33
  • @Galasko from someone with a background in most languages EXCEPT objc, i find objc archaic, convoluted and obfuscated. in perl file I/O can be done in one or two lines of code. i find mixing old legacy NSDictionary, Dictionary, NSmutableDictionary, etc a real pain in the a$$. and apple pi$$es me off by not having any decent examples in swift. i have a simple 2d array i just want to write to a plist file, this should be simple but it isn't – μολὼν.λαβέ Apr 02 '15 at 14:38
1

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!

Giacomo Orsi
  • 131
  • 8