简体   繁体   中英

Getting “<NULL>” data from core data and app crashed when we save in NSUserDefaults?

In app version 1.0 my core data has 5 attributes like attribute1, attribute2, attribute3, attribute4, attribute5 (All attributes type is transformable). It's currently available in App Store. In app version 2.0 i updated my core data DB. I added one more attribute like attribute6. I changed core data version from core data to core data2 and i changed in persistentStoreCoordinator like this.

NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

It's working fine, but at the time of app update from version 1.0 to 2.0 (first installation of new version) I'm getting “NULL” data from attribute6 (when i get data from DB) and i'm trying to save attribute6 data in NSUserDefaults, but app crashed and getting below error.

[User Defaults] Attempt to set a non-property-list object <null> as an NSUserDefaults/CFPreferences value for key MyKeyName
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object null for key MyKeyName'

Make sure you have data for attribute6 written in the DB before reading if you want it to be not empty. If you want to just save the value directly after reading from DB, and allow attribute6 to be empty, then you have to check the value for [NSNull null] before trying to save it in NSUserDefaults , NSUserDefaults doesn't accept [NSNull null] objects.

Edit: Judging from your comments, the value will be initially [NSNull null] . So you can handle it this way:

//assuming the object is named attribute
if (attribute != [NSNull null]) {
       [[NSUserDefaults standardUserDefaults] setObject:attribute forKey:MyKeyName];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM