【问题标题】:How to save an array to .plist in the App's mainBundle in swift如何在 swift 中将数组保存到 App 的 mainBundle 中的 .plist
【发布时间】:2015-01-09 10:54:54
【问题描述】:

如何使用数组类型将数组保存到 .plist?

我试试这个,但是不行

    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)

【问题讨论】:

标签: ios arrays swift plist


【解决方案1】:

您不能写入 Bundle 目录,但可以写入 Documents 目录。所以,使用这个代码!

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

当你将 writeToFile() 使用时:

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

祝你好运!

【讨论】:

    【解决方案2】:

    您无法写入 iOS 中的主包,您的 Apps 包中的所有内容都是只读的。

    [The App's bundle ] 目录包含应用程序和所有 它的资源。您无法写入此目录。阻止 篡改,捆绑目录在安装时签名。 写入此目录会更改签名并阻止您的应用 从发射。但是,您可以获得对任何 存储在应用程序包中的资源。

    考虑阅读file system programming guide,然后将您的 plist 保存到正确的位置。最好是 Documents 目录或 Library 目录。由你决定。

    【讨论】:

    • @TheParamagneticCroissant 非常感谢您,先生!那里的投票相当激进
    • 答案原来是一句话,没有回答贴出来的问题“How I can save array to .plist with array type?”。
    • @IanMacDonald 我很抱歉先生,更新后反映更多
    • 那个编程指南糟透了,原来的问题标签是swift而不是objc。
    • @GAlexander 不幸的是,Objective-C 不会很快消失,但我看不出它是用什么语言编写的指南有什么不同?该指南非常坚如磐石,但看不出仇恨来自哪里?
    猜你喜欢
    • 2014-09-25
    • 2017-05-30
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多