2

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
    you have encode it while saving and decode it after fetching.[check out this link][1] [1]: http://stackoverflow.com/a/2315972/992774 – Manish Agrawal Aug 03 '12 at 03:16

2 Answers2

1

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

Community
  • 1
  • 1
Stunner
  • 12,025
  • 12
  • 86
  • 145
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];
bitmapdata.com
  • 9,572
  • 5
  • 35
  • 43
  • 1
    This is awful, awful advice. MyObject may contain pointers to other data. Also `sizeof()` is not the correct way to find the payload size of an Objective-C object. Use NSCoding. This approach might be usable for value-semantic C structs, but would *never* be appropriate for Objective-C objects. Not only that but the `Load` code would smash the stack. OMG this is so horrible! Please no one do this! – ipmcc Aug 29 '13 at 12:33