By using the Nscoding protocol, you can implement an archive of custom classes, Nskeyedarchiver can archive our custom classes, and to implement a custom class archive, you need to implement
Encodewithcoder (encoding) and Initwithcoder (decoding)
I create a custom student class that follows the nscoding protocol to implement both methods:
student.h// userlist//// Created by Http://blog.csdn.net/yangbingbinga on 14/11/14.// Copyright (c) 2014 Http://blog.csdn.net/yangbingbinga. All rights reserved.//#import <Foundation/Foundation.h> @interface student:nsobject<nscoding> @property ( Nonatomic,strong) NSString * name; @property (Nonatomic,strong) NSString * age; @end
. m file
student.m// userlist//// Created by YB on 14/11/14.// Copyright (c) 2014 http://blog.csdn.net/ Yangbingbinga. All rights reserved.//#import "Student.h" @implementation student-(void) Encodewithcoder: (Nscoder *) acoder{ NSLog (@ "%s", __function__); [Acoder encodeObject:self.name forkey:@ "name"]; [Acoder encodeObject:self.age forkey:@ "age"]; } -(ID) Initwithcoder: (Nscoder *) adecoder{ NSLog (@ "%s", __function__); Self.name = [Adecoder decodeobjectforkey:@ "name"]; Self.age = [Adecoder decodeobjectforkey:@ "age"]; return self;} @end
We can test it directly in Appdelegate, how to archive and read the archived data:
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions{ Student * stu = [[Student alloc]init]; Stu.name = @ "123"; Stu.age = @ "3"; NSData * StuD = [Nskeyedarchiver archiveddatawithrootobject:stu];//archive, call Encodewithcoder method Student * STU1 = [ Nskeyedunarchiver unarchiveobjectwithdata:stud];//reads archived data, calls Initwithcoder NSLog (@ "stu1.name =%@", stu1.name); return YES;}
Original address: Http://blog.csdn.net/yangbingbinga
Ios-nscoding protocol, Nskeyedarchiver custom class archive using the detailed description