当我试图保存一个自定义对象时,我使用setObjectForKey方法,但是当我试图为同一个键检索它时,它返回nil。我一直在研究,我知道将自定义对象设置为NSUserDefaults有一些问题,所以我尝试使用NSKeyedArchiver类,但它仍然返回nil。

//
//  VirtualRewardsClient.swift
//  VirtualRewardsNew
//
//  Created by Dhruv Mangtani on 3/14/15.
//  Copyright (c) 2015 dhruv.mangtani. All rights reserved.
//

import UIKit

class VirtualRewardsClient{

class var sharedInstance: VirtualRewardsClient{
    struct Static{
        static var instance = VirtualRewardsClient()
    }
    return Static.instance
}

func getClass() -> Class{
    var defaults = NSUserDefaults.standardUserDefaults()
    println(defaults.objectForKey(classKey))
    if let data = defaults.objectForKey(classKey) as? NSData{
        //let unarc = NSKeyedUnarchiver(forReadingWithData: data)
        //unarc.setClass(Class.self, forClassName: "Class")
        let currentClass = NSKeyedUnarchiver.unarchiveObjectWithData(data) as Class
        println("entering")
        Class.sharedInstance.students = currentClass.students
        Class.sharedInstance.teacher = currentClass.teacher
        return currentClass

    } else {
        var newClass = Class()
        newClass.students = [Student]()
        var encodedObject: NSData = NSKeyedArchiver.archivedDataWithRootObject(newClass)
        defaults.setObject(encodedObject, forKey: classKey)
        defaults.synchronize()
        return newClass
    }
}
}

斯威夫特类
import Foundation
import UIKit

let classKey = "CLASS_KEY"

class Class: NSObject{
let defaults = NSUserDefaults.standardUserDefaults()
class var sharedInstance: Class{
    struct Static{
        static var instance: Class = VirtualRewardsClient.sharedInstance.getClass()
    }
    return Static.instance
}
var students:[Student] = [Student]()
var teacher = Teacher(currentClass: sharedInstance)

func addStudent(name: String, value: Int){
    students.append(Student(name: name, startingPoints: value))
    defaults.setObject(Class.sharedInstance, forKey: classKey)
    VirtualRewardsClient.sharedInstance.getClass()
}

func addStudent(name: String){
    students.append(Student(name: name))
    defaults.setObject(Class.sharedInstance, forKey: classKey)
    VirtualRewardsClient.sharedInstance.getClass()
}

func printClass(){
    for i in students{
        println("Student: \(i.name), Points: \(i.points)")
    }
}
}

应用程序委派:
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    /*var storyboard = UIStoryboard(name: "Main", bundle: nil)
    var vc = storyboard.instantiateViewControllerWithIdentifier("StudentsNavigationController") as UIViewController
    window?.rootViewController = vc
    println("didFinishLaunchingWithOptions\(window?.rootViewController)")
    */
    return true
}

func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     println("applicationDidEnterBackground")
}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    println("applicationWillEnterForeground")
}

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.
    println("applicationDidBecomeActive")
}

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


}

最佳答案

将类更改为VirtualRewardsClient

关于swift - 带有自定义对象的setObjectForKey方法不起作用NSUserDefaults swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29062139/

10-12 03:35