在NSUserDefault中存储自定义对象

时间:2016-05-04 05:53:56

标签: ios swift nsuserdefaults

在我的应用程序中,我执行一些异步调用,这些调用会返回一些jsons。我解析了这些响应,并填充了一些结构,如下所示:

public struct StudentInfo {

let availableExams : Int?
let course : String?
let courseLength : Int?
let department : String?
let enrolledExams : Int?
let name : String?
let surname : String?
let registrationDate : String?
let studentClass : String?
let studentId : String?

init?(json: JSON) {
    self.availableExams = "availableExams" <~~ json
    self.course = "course" <~~ json
    self.courseLength = "courseLength" <~~ json
    self.department = "department" <~~ json
    self.enrolledExams = "enrolledExams" <~~ json

    let auxName: String? = "name" <~~ json
    self.name = auxName?.firstCharacterUpperCase()

    let auxSurname: String? = "surname" <~~ json
    self.surname = auxSurname?.firstCharacterUpperCase()

    self.surname?.firstCharacterUpperCase()
    self.registrationDate = "registrationDate" <~~ json
    self.studentClass = "studentClass" <~~ json
    self.studentId = "studentID" <~~ json
}
}

我想使用NSUserDefault来存储这些对象,以便在没有互联网连接可用于执行对外部Web服务的API调用的情况下检索它们。这是一个可行的选择,还是有更简单的方法呢?

3 个答案:

答案 0 :(得分:2)

您可以使用这些功能来做您想做的事情......

+ (id)getUserDefaultsForKey:(NSString *)key{
    return [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:key]];
}


+ (void)setUserDefaults:(id)value forKey:(NSString *)key{
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:value] forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)deleteUserDefaultsForKey:(NSString *)key{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

尝试一次......但您的自定义对象应遵循以下功能。

- (void)encodeWithCoder:(NSCoder *)coder
{
    [super encodeWithCoder:coder];

    [coder encodeObject:self.property forKey:@"property"];
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        self.property = [coder decodeObjectForKey:@"property"];
    }
    return self;
}

在自定义对象中使用这两个函数,然后使用上述函数在用户默认值中保存该对象。

答案 1 :(得分:2)

要在磁盘上保存自定义对象,必须使该对象确认符合NSCoding。但结构无法确认NSCoding。 我们可以在StudentInfo结构中添加一个符合NSCoding的类:

struct StudentInfo {
let course: String
static func encode(student: StudentInfo) {
let studentClassObject = HelperClass(student: student)
NSKeyedArchiver.archiveRootObject(studentClassObject, toFile: HelperClass.path())
}
static func decode() -> StudentInfo? {
let personClassObject = NSKeyedUnarchiver.unarchiveObjectWithFile(HelperClass.path()) as? HelperClass
return personClassObject?.student
}
}

extension StudentInfo {
class HelperClass: NSObject, NSCoding {

var student: StudentInfo?

init(student: StudentInfo) {
  self. student = student
  super.init()
}

class func path() -> String {
  let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
  let path = documentsPath?.stringByAppendingString("/StudentInfo")
  return path!
}

  guard let course = aDecoder.decodeObjectForKey("course") as? String else    {     student = nil; 
 super.init(); 
 return nil 
 }

  student = StudentInfo(course: course)

  super.init()
}

func encodeWithCoder(aCoder: NSCoder) {
  aCoder.encodeObject(student!.course, forKey: "course")

    }
  }
}


let me = StudentInfo(course: "Swift",)

StudentInfo.encode(me)

let myClone = StudentInfo.decode()

firstNameLabel.text = myClone?.course

答案 2 :(得分:1)

您可以解析数据并将其存储在核心数据而不是NSUserDefaults中,以实现高效的内存管理。您可以从数据库(核心数据)获取数据,而不会出现任何互联网连接问题。将数据存储为数据库中的超越数据。