Original blog, reproduced please indicate the source
Http://blog.csdn.net/hello_hwc?viewmode=contents
Welcome to my iOS SDK detailed column
Http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html
Foreword: Nscoding is the protocol that must be followed to encode and decode the model class in iOS, which is necessary if an object is to be archived.
Nscoding to implement two methods
- initWithCoder: //解码- encodeWithCoder://编码
A simple example:
- Define a model that follows the Nscoding protocol, allowing us to store archived data (directly to plist or nsuserdefaults)
Oc
@interface mymodel:nsobject<nscoding>@property(Copy,nonatomic)NSString* NAME;@property(nonatomic)intAge@end @implementation mymodel -(Instancetype) Initwithcoder: (Nscoder *) adecoder{if( Self= [SuperInit]) { Self. Name= [Adecoder decodeobjectforkey:@"Kname"]; Self. Age= [Adecoder decodeint32forkey:@"Kage"]; }return Self;} -(void) Encodewithcoder: (Nscoder *) acoder{[Acoder encodeobject: Self. Nameforkey:@"Kname"]; [Acoder EncodeInt32: Self. Ageforkey:@"Kage"];} -(NSString*) description{return[NSStringstringwithformat:@"name:%@; age:%d ", Self. Name, Self. Age];}
Then it calls
[Super Viewdidload]; mymodel * model = [[mymodel alloc] init]; Model.name = @ "Wenchen" ; Model.age = 24 ; nsdata * data = [nskeyedarchiver Archiveddatawithrootobject:model]; mymodel * Unarchedmodel = [nskeyedunarchiver Unarchiveobjectwithdata:data ]; nslog (@ "%@" , Unarchedmodel); name : Wenchen; age : 24
Why do you write description? Because it is easy to debug
Swift implementation
Class Mymodel:nsobject,nscoding {var name:string var age:int32 init (name:string,age:int32) {self. Name= Name Self. Age= Age Super. Init()} Required init (coder Adecoder:nscoder) {self. Name= Adecoder. Decodeobjectforkey("Kname") as! String Self. Age= Adecoder. Decodeintforkey("Kage")} func Encodewithcoder (acoder:nscoder) {Acoder. Encodeobject(Self. Name, Forkey:"Kname") Acoder. Encodeint(Self. Age, Forkey:"Kage") }}
Call
letMyModel"Wenchen"24) letdata = NSKeyedArchiver.archivedDataWithRootObject(model) letNSKeyedUnarchiver.unarchiveObjectWithData(data) as! MyModel println("Name:\(unArchedModel.name); Age:\(unArchedModel.age)")
Copyright NOTICE: This article is for bloggers original article, if you need to reprint please indicate the source
IOS SDK detailed nscoding protocol