我的应用程序与EXC_BAD_INSTRUCTION(code=EXC_i386_INVOP, subcode=0x0)
. 控制台记录(lldb)
. 我正在尝试NSUserDefaults
使用NSKeyedArchiver
and NSKeyedUnarchiver
。我试图序列化的类是 的子类NSManagedObject
,所以我不能直接序列化它(实际上我可以,但我不能反序列化它,因为它需要一个NSManagedObjectContext
)。但实际上,如果有办法直接序列化类,请这么说=)
为了解决这个问题,我创建了一个与对象具有相同属性的 NSDictionary,然后对其进行序列化。就是这样:
var userDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults();
var data: NSData? = userDefaults.dataForKey(DefaultSessionProfileKey);
// Only saves if necessary
if data == nil {
var dict: NSDictionary = [
"firstName": profile.firstName,
"lastName": profile.lastName,
"nameFormat": profile.nameFormat,
"gender": profile.gender,
"birthday": profile.birthday,
"picture": profile.picture,
"uid": profile.uid
];
// Save the profile to user defaults
data = NSKeyedArchiver.archivedDataWithRootObject(dict);
userDefaults.setObject(data, forKey: DefaultSessionProfileKey);
}
然后反其道而行之。当从标准用户默认值中检索数据时,此代码在第二行崩溃:
var userDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults();
var data: NSData? = userDefaults.dataForKey(DefaultSessionProfileKey);
var profile: Profile?;
if data != nil {
// Unserialize the profile data. We must serialize/deserialize an NSDictionary instead of directly using a Profile instance because Profile is NSMutableObject, which means that it cannot exist without an NSManagedObjectContext. We don't have one for the serialization/deserialization process, so we generate this dictionary first
var dict = NSKeyedUnarchiver.unarchiveObjectWithData(data) as NSDictionary;
if dict != nil {
// Create the profile instance
var appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate;
var entity: NSEntityDescription = NSEntityDescription.entityForName("Profile", inManagedObjectContext: appDelegate.managedObjectContext);
var profile: Profile = Profile(entity: entity, insertIntoManagedObjectContext: appDelegate.managedObjectContext);
profile.firstName = dict.objectForKey("first_name") as String;
profile.lastName = dict.objectForKey("last_name") as String;
profile.nameFormat = dict.objectForKey("name_format") as String;
profile.gender = dict.objectForKey("gender") as String;
profile.birthday = dict.objectForKey("birthday") as NSDate;
profile.picture = dict.objectForKey("picture") as String;
profile.uid = dict.objectForKey("uid") as String;
}
else {
// A profile exists in user defaults, but it's not a valid profile, so we take the chance to clean up
userDefaults.removeObjectForKey(DefaultSessionProfileKey);
}
}