我認爲你的會話課沒有編碼和解碼方法。 如果你的會話是自定義類,那麼你應該寫下面兩種方法,沒有存檔將無法工作。
代碼:
目標C版本:
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.session_property1 forKey:@"session_property1"];
[encoder encodeObject:self.session_property2 forKey:@"session_property2"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
//decode properties, other class vars
self.ession_property1 = [decoder decodeObjectForKey:@"ession_property1"];
self.ession_property2 = [decoder decodeObjectForKey:@"ession_property2"];
}
return self;
}
這裏session_property1和session_property2被視爲字符串,如果你的變量是不是需要相應地格式化字符串等。
這些在你砍上下課後,如果您將使用archiveData
方法,你這樣做的話,那將歸檔的數據,然後可以將這些數據設置爲NSUserDefault
斯威夫特版本:
required init(coder decoder: NSCoder) {
self.state = decoder.decodeObject(forKey: "state") as? String
self.country = decoder.decodeObject(forKey: "country") as? String
self.zip = decoder.decodeObject(forKey: "zip") as? String
self.locality = decoder.decodeObject(forKey: "locality") as? String
self.city = decoder.decodeObject(forKey: "city") as? String
self.latitude = decoder.decodeObject(forKey: "latitude") as? Double
self.longitude = decoder.decodeObject(forKey: "longitude") as? Double
}
func encode(with coder: NSCoder) {
coder.encode(state, forKey: "state")
coder.encode(country, forKey: "country")
coder.encode(zip, forKey: "zip")
coder.encode(locality, forKey: "locality")
coder.encode(city, forKey: "city")
coder.encode(latitude, forKey: "latitude")
coder.encode(longitude, forKey: "longitude")
}
我希望它能幫助你。 快樂編碼...
什麼是'session'? – Aaron
NSUserDefaults支持以下數據類型:NSString,NSNumber,NSDate,NSArray,NSDictionary和NSData http://stackoverflow.com/questions/37980432/swift-3-saving-and-retrieving-custom-object-from-userdefaults – Rivendell