如何在NSUserDefaults中的自定义类中存储我的对象?

时间:2015-04-28 16:11:18

标签: ios swift nsuserdefaults

我有一个自定义类,其中包含与该类有关的对象:

import UIKit;

var managerObj = Manager() //Instance of an FUT class

/*************************************************************
*
* Class: Manager
* Description: This class handles all of the data
*              in the application. It also stores the
*              information.
*
**************************************************************/
class Manager {

    // Get the current time when the user starts a ride.
    var beginTime = NSCalendar.currentCalendar().components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: NSDate())

    // Get the HTML/CSS/JavaScript template path for read/write
    let coverTemplateFilePath = NSBundle.mainBundle().pathForResource("CoverTemplate", ofType: "txt")
    let issueTemplateFilePath = NSBundle.mainBundle().pathForResource("Template", ofType: "txt")

    var Mgr = RideManager() //Instance of a RideManager class
    var voiceRec = SKRecognizer()

    var issueEditFlag : Bool = false //Flag if user is trying to edit issue
    var issueBeingEdited = 0 //The item in the array user is trying to edit

    //Sets the values for the ride
    func setRideVariables(Ride:String, Tester:String, Vehicle:String, SW:String, HW:String, startTime:String, startMiles:String, Date:String){
        //set object values here...
    }
}

在我添加该对象的字段后,我需要找出一种保存该信息的方法,以便在程序退出时,可以轻松加载信息。我尝试将futReport对象保存到AppDelegates.swift文件中的NSUserDefaults中,如下所示:

func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

        var appDefault = NSUserDefaults.standardUserDefaults()
        appDefault.setValue(managerObj, forKey: "managerObj")
        appDefault.synchronize()
    }

然后我尝试在应用程序再次变为活动状态时加载对象信息,如下所示:

func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

        var appDefault = NSUserDefaults.standardUserDefaults()
        if (appDefault.valueForKey("managerObj") != nil) {
            managerObj = appDefault.valueForKey("managerObj") as Manager!
        }
    }

但它始终在managerObj = appDefault.valueForKey("managerObj") as Manager!出错,我认为这是因为valueForKey()方法支持返回字符串或整数而不是类FUTManager中的对象。有没有人有任何想法?

我尝试搜索有类似问题的人,但我找不到解决方案。

谢谢!

编辑:我根本不熟悉Objective-C。如果你能在Swift中解释它,那就太棒了!!

1 个答案:

答案 0 :(得分:0)

存储对象

var customObject = CustomClass()

let encodedObj = NSKeyedArchiver.archivedDataWithRootObject(customObject)
NSUserDefaults.standardUserDefaults().setObject(encodedObj, forKey: "encodedObjectKey")

检索存储的对象

let encodedObj = NSUserDefaults.standardUserDefaults().objectForKey("encodedObjectKey") as! NSData
var customObject = NSKeyedUnarchiver.unarchiveObjectWithData(encodedObj) as! CustomClass
相关问题