【问题标题】:setObjectForKey method with custom objects doesn't work NSUserDefaults swift带有自定义对象的 setObjectForKey 方法不起作用 NSUserDefaults swift
【发布时间】:2015-03-15 15:05:45
【问题描述】:

当我尝试保存自定义对象时,我使用 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
    }
}
}

类.swift

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


}

【问题讨论】:

    标签: swift nsuserdefaults


    【解决方案1】:

    将类更改为 VirtualRewardsClient

    【讨论】:

    • 在哪里? Class 和 VirtualRewardsClient 都有一个共享实例 btw
    猜你喜欢
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    相关资源
    最近更新 更多