0

I have a custom class with an object pertaining to that class:

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...
    }
}

After I add the fields for that object I need to figure out a way to save that information so that if the program exits, the information can be easily loaded. I try to save the futReport object into NSUserDefaults in the AppDelegates.swift file like so:

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()
    }

Then I try to load the object information once the application becomes active again like so:

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!
        }
    }

But it keeps erroring out at managerObj = appDefault.valueForKey("managerObj") as Manager! I'm assuming it is because the valueForKey() method is support to return a string or integer and not an object from class FUTManager. Does anyone have any ideas?

I tried searching for someone who had a similar issue but I couldn't find a solution.

Thank you!

EDIT: I'm not familiar with Objective-C at all. If you could please explain it in Swift, that would be great!!

MB41
  • 552
  • 2
  • 8
  • 24
  • 1
    possible duplicate of [How to store custom objects in NSUserDefaults](http://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults) – Wez Apr 28 '15 at 16:25

1 Answers1

0

Storing an Object,

var customObject = CustomClass()

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

Retrieving stored Object,

let encodedObj = NSUserDefaults.standardUserDefaults().objectForKey("encodedObjectKey") as! NSData
var customObject = NSKeyedUnarchiver.unarchiveObjectWithData(encodedObj) as! CustomClass
Sean
  • 2,106
  • 2
  • 16
  • 24
itsji10dra
  • 4,603
  • 3
  • 39
  • 59
  • Answers should be posted in the expected language. Don't make everyone else do the conversion. – rmaddy Apr 28 '15 at 16:30
  • Plus, this answer doesn't actually address to specific error mentioned in the question. – rmaddy Apr 28 '15 at 16:31
  • 1
    Oopss.. Edited it. Sorry about that :) – itsji10dra Apr 28 '15 at 16:32
  • Yeah, I'm not familliar with Objective-c at all. Would it be possible to explain it in swift? Thank you very much!! Edit: thank you!! – MB41 Apr 28 '15 at 16:32
  • Also would need to implement encodeWithCoder and initWithCoder in the custom class, no? – shim Apr 28 '15 at 16:37
  • @RoNiT I get an error at the NSKeyedArchiver.archivedDataWithRootObject(customObject) line: `2015-04-28 12:53:43.889 FUTRecorder[3662:53300] *** NSForwarding: warning: object 0x7ff239eee240 of class 'CustomClass' does not implement methodSignatureForSelector: -- trouble ahead Unrecognized selector -[CustomClass replacementObjectForKeyedArchiver:]` any ideas why I'm getting this error? – MB41 Apr 28 '15 at 16:53
  • @shim what is encodeWithCoder and initWithCoder? I don't have those methods in my class, maybe that is why I'm getting the error? – MB41 Apr 28 '15 at 16:55
  • @Billy Is your class a subclass of `NSObject` ? – itsji10dra Apr 28 '15 at 16:56
  • @RoNiT No, if you look at my original post, my class is setup like this `class Manager {...}` do I need it to be like this: `class Manager : NSObject {...}`? would I need encodeWithCoder and initWithCoder methods defined in my class? – MB41 Apr 28 '15 at 16:58
  • 1
    Check this out. http://stackoverflow.com/questions/26469457/saving-custom-swift-class-with-nscoding-to-userdefaults – Sean Apr 28 '15 at 18:26