Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I found out one alternative, before save, I encode the root object (<code>NSArray</code> object) using <code>NSKeyedArchiver</code>, which ends with <code>NSData</code>. Then use UserDefaults save the <code>NSData</code>. </p> <p>When I need the data, I read out the <code>NSData</code>, and use <code>NSKeyedUnarchiver</code> to convert <code>NSData</code> back to the object. </p> <p>It is a little cumbersome, because i need to convert to/from <code>NSData</code> everytime, but it just works.</p> <p>Here is one example per request:</p> <p>Save:</p> <pre><code>NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSMutableArray *arr = ... ; // set value NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr]; [defaults setObject:data forKey:@"theKey"]; [defaults synchronize]; </code></pre> <p>Load:</p> <pre><code>NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSData *data = [defaults objectForKey:@"theKey"]; NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data]; </code></pre> <p>The element in the array implements </p> <pre><code>@interface CommentItem : NSObject&lt;NSCoding&gt; { NSString *value; } </code></pre> <p>Then in the implementation of <code>CommentItem</code>, provides two methods:</p> <pre><code>-(void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:value forKey:@"Value"]; } -(id)initWithCoder:(NSCoder *)decoder { self.value = [decoder decodeObjectForKey:@"Value"]; return self; } </code></pre> <p>Anyone has better solution?</p> <p>Thanks everyone. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload