我正在为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.")
}
任何人都有我的代码中有什么错误的想法?
答案 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.")
}