How to save My Data Type in NSUserDefault?

穿精又带淫゛_ 提交于 2019-12-07 20:06:33

问题


I want to save My Data Type temporary in NSUserDefault. this data later pull back.

I tried to following code.

MyObject *myObject = [[MyObject alloc] init];

[[NSUserDefaults standardUserDefaults] setObject:myObject forKey:@"kMyObject"];

but console show to text me 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 to force pull out from NSUserDefault.

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

but, not give back original data. (I've Checked the NSLog, returns Null.)

How to solve this problem? I only prefer save to NSUserDefaults. not recommended to me using CoreData.


回答1:


Many Developer recommend to NSKeyedArchiver Taking advantage of the concept. but it must implement protocols to NSCopy NSCoding and because some can be complex. More than that there is an easier way. refer a 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];



回答2:


You have to make sure that all objects contained within your MyObject instance are property list (plist) objects. Please see this post.



来源:https://stackoverflow.com/questions/11788408/how-to-save-my-data-type-in-nsuserdefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!