使用swift保存和加载自定义对象数组的最佳方法是什么?

时间:2016-02-16 07:10:12

标签: swift

我有一个应用程序可以通过按地图来保存用户提供的位置。自定义类看起来像这样:

class Places {
var name = ""
var latitude : CLLocationDegrees
var longitude : CLLocationDegrees

init(name: String, latitude: CLLocationDegrees, longitude:CLLocationDegrees) {

self.name = name
self.latitude = latitude
self.longitude = longitude
}

然后在第一个viewController,一个TableView之外,我设置了这些自定义对象的空数组。

var places = [Places]()

在下一个视图控制器上,长按地图后会创建这些对象。

var newPlace = Places(name: title, latitude: newCoordinate.latitude, longitude: newCoordinate.longitude)

            places.append(newPlace)

该应用效果很好但关闭时没有任何内容保存。我尝试将数组保存到NSUserDefaults,但显然无法使用自定义对象数组。保存此数组然后加载它的最有效方法是什么?

2 个答案:

答案 0 :(得分:1)

对于此任务,我会选择NSCoding和NSKeyedArchive。

有一个article on NSHipster about different storage options讨论CoreData,NSUserDefaults和NSKeyedArchive的优缺点,并为每种方法提供示例代码。

答案 1 :(得分:1)

我刚将这个实现到我的程序中。我无法确定它是否适用于var类型CLLocationDegrees,但我已经完成了您尝试对其他变量类型执行的操作。

NSUser默认设置应该可以使用,但您必须将它们放在您的课​​程中

class Places : NSObject, NSCoding {// Must inherit NSObject and implement NSCoding protocol

override init() {
    //must be empty initializer
}

//include all properties you want to store
required convenience init?(coder aDecoder: NSCoder) {
    self.init()
    self.name = aDecoder.decodeObjectForKey("name") as? String
    self.longitude = aDecoder.decodeObjectForKey("latitude") as? CLLocationDegrees
    self.latitude = aDecoder.decodeObjectForKey("longitude") as? CLLocationDegrees

}

//include all properties you want to load
func encodeWithCoder(aCoder: NSCoder) {

    aCoder.encodeObject(self.name, forKey: "name")
    aCoder.encodeObject(self.latitude, forKey: "latitude")
    aCoder.encodeObject(self.longitude, forKey: "longitude")
 }

当您想要保存时。

let placesData = NSKeyedArchiver.archivedDataWithRootObject(places) //convert to NSdata
        NSUserDefaults.standardUserDefaults().setObject(placesData, forKey: "places") // required for array's / dicts of objects
        NSUserDefaults.standardUserDefaults().synchronize() // actual saving

然后当你想使用它时

loadedPlaces = NSUserDefaults.standardUserDefaults().objectForKey("places") as? NSData {//grab data out of NSUserDefaults and convert it to NSData

        print("user has customized heroes")
        places = (NSKeyedUnarchiver.unarchiveObjectWithData(loadedPlaces) as? [Places])! // unarchive it from data to what it used to be
相关问题