What is nscoding?
Nscoding is what we commonly known as the archive, the archive means that the project in a section of the object's code stored in a file, there are two ways to archive, one is on the Mac of the archive, one is on the iOS archive, today only the archive on the Mac.
Here are the methods involved.
NSData
nskeyedarchiver Archiveddatawithrootobject: This means storing an object in binary form.
writetofile: atomically: This means that the stored path and whether it is stored.
The following is a simple example:
First we want to create a new class, here we need to pay attention to a thing, the newly created class inherits with NSObject, but also implements the nscoding protocol.
#import <Foundation/Foundation.h>@interface human:nsobject <NSCoding>{ @private int _age; *_name; *_child;} @property (nonatomic, assign)int** child; @end
Implement the methods in the Nscoding protocol.
#import "Human.h"@implementationHuman@synthesizeAge ;@synthesizename;@synthesizeChild ;//implement the Archive method in the protocol.- (void) Encodewithcoder: (Nscoder *) Acoder {[Acoder encodeint:age forkey:@"_age"]; [Acoder encodeobject:name Forkey:@"_name"]; [Acoder encodeobject:child Forkey:@"_child"];}//Implement the solution file method in the protocol.- (ID) Initwithcoder: (Nscoder *) adecoder{if(self =[Super Init]) {Self.age= [Adecoder Decodeintforkey:@"_age"]; Self.name= [Adecoder Decodeobjectforkey:@"_name"]; Self.child= [Adecoder Decodeobjectforkey:@"_child"]; } returnSelf ;}@end
Initialize the object and parameters to be archived in the main function.
#import<Foundation/Foundation.h>#import "Human.h"intMainintargcConst Char*argv[]) {@autoreleasepool {Human*human1 =[[Human alloc]init]; Human*human2 =[[Human alloc]init]; Human1.age= -; Human1.name=@"xiaoming"; Human1.child=human2; NSData*data1 =[Nskeyedarchiver Archiveddatawithrootobject:human1]; [Data1 WriteToFile:@"/users/cain/desktop/objective-c/Experiment Code/File operation/Archive/human/human.txt"Atomically:yes]; NSLog (@"%@", data1);
}
return 0;
}
How nscoding is used---archiving on your Mac.