将NSMutableArray存储到swift中的plist时失败

时间:2015-03-31 14:59:29

标签: swift nsmutablearray plist

我正在为iphone写一个快捷的代码。在我的应用程序中,我需要存储一些朋友信息。目前我使用plist来存储数据。我已经提到了很多从plist读取/写入NSMutableArray的例子,但是当我试图存储一个NSMutableArray它只是不起作用。

以下是我的代码,最后结果是" nil"。

let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filename = path.stringByAppendingPathComponent("FriendList.plist")

var FM = NSFileManager()
if FM.createFileAtPath(filename, contents: nil, attributes: nil) {
    if (arrayToBeStored?.writeToFile(filename, atomically: false) != nil) { 
        if NSFileManager().fileExistsAtPath(filename){
            let arrayFromPlist = NSMutableArray(contentsOfFile: filename)

            //everything goes well except "arrayFromPlist" is just nil.

            println(arrayFromPlist) 
        }else{
            println("Plist was not actually created!")
        }
    }else{
        println("Failed to store the array into plist.")
    }  
}else{
    println("Failed to create file.")
}

任何人都有我的代码中有什么错误的想法?

1 个答案:

答案 0 :(得分:0)

" arrayToBeStored.writeToFile"返回一个布尔值,因此它与" nil"无法比较。

    let arrayToBeStored = NSArray(object: ["test1", "test2"])
    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
    let filename = path.stringByAppendingPathComponent("FriendList.plist")
    var FM = NSFileManager()
    if FM.createFileAtPath(filename, contents: nil, attributes: nil) {
        if arrayToBeStored.writeToFile(filename, atomically: false) {
            if NSFileManager().fileExistsAtPath(filename){
                let arrayFromPlist = NSMutableArray(contentsOfFile: filename)
                println(arrayFromPlist!)  // => test1, test2
            }else{
                println("Plist was not actually created!")
            }
        } else {
            println("Failed to store the array into plist.")
        }
    }else{
        println("Failed to create file.")
    }

Xcode 6.2版本:

let arrayToBeStored = NSArray(object: ["test1", "test2"])
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filename = path.stringByAppendingPathComponent("FriendList.plist")
var FM = NSFileManager()
if FM.createFileAtPath(filename, contents: nil, attributes: nil) {
    if arrayToBeStored.writeToFile(filename, atomically: false) {
        if NSFileManager().fileExistsAtPath(filename) {
            let arrayFromPlist = NSMutableArray(contentsOfFile: filename)
            println(arrayFromPlist![0][0])  // => test1
        }else{
            println("Plist was not actually created!")
        }
    } else {
        println("Failed to store the array into plist.")
    }
}else{
    println("Failed to create file.")
}

enter image description here