Swift中数组对象的持久化存储

3
我可以帮助您创建读/写一些对象到文件中的方法,以实现持久性存储。在过去的三天里,我一直被这个问题卡住了。这是我的进展:
我的对象:
class Item: NSObject {
var name : String = ""
var link : String = ""
var state : String = ""
var type : String = ""
var selected = false

func createItemWith(name:String, link:String, state:String, type:String) {
    self.name = name
    self.link = link
    self.state = state
    self.type = type
}
}

然后我将它添加到一个数组中。
self.itemsArray.addObject(item)

现在,每个对象代表集合视图中的一个单元格,在这里用户可以与之交互。
   func collectionView(collectionView: UICollectionView,
    didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
        var cellCheckedImage = cell!.contentView.viewWithTag(20) as! UIImageView
        if ((itemsArray.objectAtIndex(indexPath.row) as! Item).selected == false) {
            cellCheckedImage.image = UIImage(named:"Checked")
            self.selectedItemsArray.append(itemsArray.objectAtIndex(indexPath.row) as! Item)
            (itemsArray.objectAtIndex(indexPath.row) as! Item).selected = true
        } else if ((itemsArray.objectAtIndex(indexPath.row) as! Item).selected == true) {
            cellCheckedImage.image = UIImage(named:"Unchecked")
            (itemsArray.objectAtIndex(indexPath.row) as! Item).selected = false
        }
}

现在,您可以看到用户交互的项目将移动到第二个数组中。
self.selectedItemsArray.append(itemsArray.objectAtIndex(indexPath.row) as! Item)

这是

   var selectedItemsArray = [Item]()

现在,我有一个第二个类,它应该将前面的数组写入文件

import Foundation

private let _SelectedItemsSharedInstance = SelectedItems()

class SelectedItems: NSObject {

private var itemsKey = "items"
var selectedItems = Array("")

class var sharedInstance: SelectedItems {
    return _SelectedItemsSharedInstance
}

func loadItemsFromFile() {
    // getting path 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths[0] as! String
    let path = documentsDirectory.stringByAppendingPathComponent("SelectedItems.plist")
    let fileManager = NSFileManager.defaultManager()
    //check if file exists
    if(fileManager.fileExistsAtPath(path)) {


    }
}

func writeItemsToFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths.objectAtIndex(0) as! NSString
    let path = documentsDirectory.stringByAppendingPathComponent("SelectedItems.plist")
}
}

这是我卡住的地方。我该如何将selectedItems写入和读取到文件中?
更新:这是它的工作方式 我的对象:
class Item: NSObject {
var name : NSString = ""
var link : NSString = ""
var state : NSString = ""
var type : NSString = ""
var selected = false

func createItemWith(name:String, link:String, state:String, type:String) {
    self.name = name
    self.link = link
    self.state = state
    self.type = type
}

init(name: NSString, link: NSString, state: NSString, type: NSString)
{
    self.name = name
    self.link = link
    self.state = state
    self.type =  type
}

required init(coder aDecoder: NSCoder) {
    self.link = aDecoder.decodeObjectForKey("link") as! NSString as String
    self.name = aDecoder.decodeObjectForKey("name") as! NSString as String
    self.state = aDecoder.decodeObjectForKey("state") as! NSString as String
    self.type = aDecoder.decodeObjectForKey("type") as! NSString as String
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(link, forKey: "link")
    aCoder.encodeObject(name, forKey: "name")
    aCoder.encodeObject(name, forKey: "state")
    aCoder.encodeObject(name, forKey: "type")
}

}

以及编写和读取它们的方法

func loadItemsFromFile() {
    // getting path 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths[0] as! String
    let path = documentsDirectory.stringByAppendingPathComponent("SelectedItems.txt")
    let fileManager = NSFileManager.defaultManager()
    println(path)
    if(!fileManager.fileExistsAtPath(path)) {
        // If it doesn't, copy it from the default file in the Bundle
        if let bundlePath = NSBundle.mainBundle().pathForResource("SelectedItems", ofType: "txt") {
            let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
            if let data = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [String] {
                self.selectedItemsArray = data
            }
        }
    }
    println(self.selectedItemsArray.description)
}

func writeItemsToFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths.objectAtIndex(0) as! NSString
    let path = documentsDirectory.stringByAppendingPathComponent("SelectedItems.txt")
    NSKeyedArchiver.archiveRootObject(self.selectedItemsArray, toFile: path)

}

你尝试使用 writeToFile: 方法了吗? - Marius Fanu
当然可以,但是写入的文件是空的。我想当我写入和读取数据时需要进行编码和解码。 - trusk
1个回答

1
您可以使用NSKeyedArchiverNSKeyedUnarchiver将数组存储到文件中。类似于这样的代码:
func applicationWillTerminate(aNotification: NSNotification) {
    NSKeyedArchiver.archiveRootObject(self.myArray, toFile: "a/file/path")
}

func applicationDidFinishLaunching(aNotification: NSNotification) {
    if let data = NSKeyedUnarchiver.unarchiveObjectWithFile("a/file/path") as? [String] {
        self.myArray = data
    }
}

在这个例子中,我将它用在AppDelegate方法内部,但你可以在应用程序的任何地方使用它。

谢谢!这样做可以了,但是需要在我的对象类中实现init和encodeWithCoder。我会更新父问题以反映我所做的更改! - trusk
哎呀,确实我忘了提到那个细节。 - Eric Aya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接