Swift 中对象数组的持久存储
Persistant storage for array of objects in Swift
我需要帮助创建 reading/writing 一些对象到文件的方法,以进行持久存储。在过去的三天里,我一直坚持这一点。这是我得到的:
我的对象:
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]()
现在,我有第二个 class 应该将前一个数组写入文件
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)
}
您可以使用 NSKeyedArchiver
和 NSKeyedUnarchiver
将数组存储到文件中。像这样:
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 方法中使用它,但您可以在应用程序的任何位置使用它。
我需要帮助创建 reading/writing 一些对象到文件的方法,以进行持久存储。在过去的三天里,我一直坚持这一点。这是我得到的:
我的对象:
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]()
现在,我有第二个 class 应该将前一个数组写入文件
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)
}
您可以使用 NSKeyedArchiver
和 NSKeyedUnarchiver
将数组存储到文件中。像这样:
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 方法中使用它,但您可以在应用程序的任何位置使用它。