ios - how can store custom objects in NSUserDefaults -


i apologize duplicate question . new in ios . want store custom objects in userdefaults. using objective-c .

thanks in advance

first create custom class below.

customobject.h

#import <foundation/foundation.h>  @interface customobject : nsobject<nscoding>  @property(strong,nonatomic)nsstring *name;  @end  

customobject.m

#import "customobject.h"  @implementation customobject    - (void)encodewithcoder:(nscoder *)encoder {     //encode properties, other class variables, etc     [encoder encodeobject:self.name forkey:@"name"];  }  - (id)initwithcoder:(nscoder *)decoder {     if((self = [super init])) {         //decode properties, other class vars         self.name = [decoder decodeobjectforkey:@"name"];      }     return self; } 

then create customobject class object , store in nsuserdefaults

stored object this

customobject *object =[customobject new]; object.name = @"test";  nsmutablearray *arr = [[nsmutablearray alloc]init]; [arr  addobject:object];  nsdata *encodedobject = [nskeyedarchiver archiveddatawithrootobject:arr]; nsuserdefaults *defaults = [nsuserdefaults standarduserdefaults]; [defaults setobject:encodedobject forkey:@"storeobject"]; [defaults synchronize]; 

get custom object nsuserdefaults this

 nsdata *storedencodedobject = [defaults objectforkey:@"storeobject"];         nsarray *arrstoreobject = [nskeyedunarchiver unarchiveobjectwithdata:storedencodedobject];         (int i=0; i<arrstoreobject.count; i++)         {             customobject *storedobject = [arrstoreobject objectatindex:i];             nslog(@"%@",storedobject.name);          } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -