How to save my data type in NSUserDefault?

I want to save My Data Type temporarily in NSUserDefault. this data is later backtracked.

I tried to execute the following code.

MyObject *myObject = [[MyObject alloc] init]; [[NSUserDefaults standardUserDefaults] setObject:myObject forKey:@"kMyObject"]; 

but the console will show me the following message.

 -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '<MyObject: 0x4aadb0>' of class 'MyObject'. Note that dictionaries and arrays in property lists must also contain only property values. 

I can ignore these messages and force pull them out of NSUserDefault.

 MyObject *getObject = [[NSUserDefaults standardUserDefaults] objectForKey:@"kMyObject"]; 

but do not return the original data. (I checked NSLog, returns Null.)

How to solve this problem? I prefer to keep only NSUserDefaults. I am not recommended to use CoreData.

+2
source share
2 answers

Many developers recommend NSKeyedArchiver to use this concept. but it needs to implement NSCopy NSCoding protocols because some of them can be complicated. Moreover, there is an easier way. see the following code.

Save

  MyObject *myObject = [[MyObject alloc] init]; NSData *myObjectData = [NSData dataWithBytes:(void *)&myObject length:sizeof(myObject)]; [[NSUserDefaults standardUserDefaults] setObject:myObjectData forKey:@"kMyObjectData"]; 

load

  NSData *getData = [[NSData alloc] initWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"kMyObjectData"]]; MyObject *getObject; [getData getBytes:&getObject]; 
+1
source

You need to make sure that all objects contained in your MyObject instance are property objects (plist). See this post .

+1
source

Source: https://habr.com/ru/post/1499604/


All Articles