Swift中对象数组的持久存储

时间:2015-04-17 12:56:13

标签: ios arrays swift nsdata

我需要帮助创建用于将某些对象读/写到文件中的方法,以用于持久存储。在过去的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)

}

1 个答案:

答案 0 :(得分: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方法中使用它,但您可以在应用程序的任何位置使用它。