NSCoding協議的編碼與解碼

weixin_34075551發表於2016-02-16

---------------------------------------------點h檔案

#import

@interfaceperson :NSObject

@property(nonatomic,copy)NSString*name;

@property(nonatomic,copy)NSString*phoneNum;

@end

------------------------------------------------------------點m檔案

#import"person.h"

@implementationperson

//編碼

-(void)encodeWithCoder:(NSCoder*)aCoder

{

[aCoderencodeObject:_nameforKey:@"name"];

[aCoderencodeObject:_phoneNumforKey:@"num"];

NSLog(@"------1編碼");

}

//譯碼

-(id)initWithCoder:(NSCoder*)aDecoder

{

self=[super  init];

if(self) {

self.name=[aDecoderdecodeObjectForKey:@"name"];

self.phoneNum=[aDecoderdecodeObjectForKey:@"num"];

NSLog(@"解碼");

}

returnself;

}

-------------------------------------------------

NSFileManager*fileManage=[NSFileManagerdefaultManager];

NSString*filepath=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/a"];

BOOLisExists=[fileManagefileExistsAtPath:filepath];

if (isExists) {

dataArray=[NSKeyedUnarchiverunarchiveObjectWithFile:filepath];解檔

}else{

dataArray=[[NSMutableArrayalloc]initWithCapacity:0];

}

---------------------------------------------------------歸檔

NSString*filepath=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/a"];

NSData*data=[NSKeyedArchiverarchivedDataWithRootObject:dataArray];

//不能直接寫入內部,所以要用到轉化,成data才能寫入呼叫了NScoding協議方法;

[data writeToFile:filepath  atomically:YES];//歸檔

相關文章