Nsuserdefaults reading and writing custom objects
Nsuserdefaults can access a few short messages.
For example, deposit and then read out a string to Nsuserdefaults:
View Plaincopy to Clipboardprint?
NSString *string = [NSString stringwithstring @ "hahaha"];
Nsuserdefaults *ud = [Nsuserdefaults standarduserdefaults];
[UD setobject:string forkey:@ "MyKey"];
NSString *value;
Value = [ud objectforkey: "MyKey"];
But not all things can be put in. Nsuserdefaults only supports: NSString, NSNumber, NSDate, Nsarray, Nsdictionary.
If you save a custom class in a Nsarray, and then save it in Nsuserdefaults, it will not succeed. Do not believe can try, if you succeed please tell me.
What about that?
The method I found is to have this custom class implement <NSCoding> protocol-(ID) Initwithcoder: (Nscoder *) Coder method and-(void) Encodewithcoder: (Nscoder *) The Coder method (the OBJ-C protocol protocol is the Java Interface interface, which is the pure virtual function of C + +), then encodes the custom class object into NSData and reads from Nsuserdefaults.
Sticky code:
Suppose there is such a simple class object
View Plaincopy to Clipboardprint?
@interface Businesscard:nsobject <nscoding>{
NSString *_firstname;
NSString *_lastname;
}
@property (nonatomic, retain) NSString *_firstname;
@property (nonatomic, retain) NSString *_lastname;
@end;
@implementation Businesscard
@synthesize _FirstName, _lastname;
-(void) dealloc{
[_FirstName release];
[_lastname release];
[Super Dealloc];
}
-(ID) Initwithcoder: (Nscoder *) coder
{
if (self = [super init])
{
Self._firstname = [Coder decodeobjectforkey:@ "_FirstName"];
Self._lastname = [Coder decodeobjectforkey:@ "_lastname"];
}
return self;
}
-(void) Encodewithcoder: (Nscoder *) coder
{
[Coder encodeobject:_firstname forkey:@ "_FirstName"];
[Coder encodeobject:_lastname forkey:@ "_lastname"];
}
@end
And then re-access the carrier via NSData:
View Plaincopy to Clipboardprint?
Businesscard *BC = [[Businesscard alloc] init];
Nsuserdefaults *ud = [Nsuserdefaults standarduserdefaults];
NSData *udobject = [Nskeyedarchiver ARCHIVEDDATAWITHROOTOBJECT:BC];
[UD setobject:udobject forkey:@ "Mybusinesscard"];
[BC release];
Udobject = nil;
Udobject = [ud objectforkey:@ "Mybusinesscard"];
BC = [Nskeyedunarchiver unarchiveobjectwithdata:udobject];
The above code is intercepted by another program and has not been tested, but that's what it means.
If a custom class is made up of another custom class object, all nested classes will implement <NSCoding>.
One of the methods of storing data: Nsuserdefaults Read and write