NSCoding Protocol Reference

来源:互联网 发布:多系统基础数据同步 编辑:程序博客网 时间:2024/06/09 19:27

NSCoding Protocol Reference

encodeWithCoder:

Encodes the receiver using a given archiver. (required)

- (void)encodeWithCoder:(NSCoder *)encoder
Parameters
encoder

An archiver object.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSObject.h

initWithCoder:

Returns an object initialized from data in a given unarchiver.(required)

- (id)initWithCoder:(NSCoder *)decoder
Parameters
decoder

An unarchiver object.

Return Value

self, initialized using the datain decoder.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSObject.h

NSCoding协议中只有两个方法,都是require的方法,一个是把本身的类进行转码,一个是逆转换成类对象,返回一个对象,我们实战一下这个协议的用法,看看是否好用,首先写一个自定义Student类:

@interfaceStudent : NSObject<NSCoding>

@property (nonatomic, retain) NSString *name;

@property (nonatomic, retain) NSString *ID;


-(Student *)initWithName :(NSString*)newName 

                 and : (NSString *)newID;

@end

Student类需要实现协议NSCoding,.m文件中是这样的:

 

@implementationStudent

@synthesize name = _name,ID = _ID;

 

//初始化学生类

-(Student *)initWithName:(NSString *)newName and:(NSString *)newID{

   self = [super init];

   if (self) {

       self.name = newName;

       self.ID= newID;

    }

   return self;

}

//学生类内部的两个属性变量分别转码

-(void)encodeWithCoder:(NSCoder *)aCoder{

   [aCoder encodeObject:self.name forKey:@"name"];

   [aCoder encodeObject:self.IDforKey:@"ID"];

}

//分别把两个属性变量根据关键字进行逆转码,最后返回一个Student类的对象

-(id)initWithCoder:(NSCoder *)aDecoder{

   if (self = [super init]) {

       self.name = [aDecoder decodeObjectForKey:@"name"];

       self.ID= [aDecoder decodeObjectForKey:@"ID"];

    }

   return self;

}


@end


自定义类Student实现了NSCoding协议以后,就可以进行归档转换了,具体实现:

 

   Student *stu1 = [[Student alloc]initWithName:@"124" and:@"111"];//学生对象stu1

   Student *stu2 = [[Student alloc]initWithName:@"223" and:@"222"];//学生对象stu2

   NSArray *stuArray =[NSArray arrayWithObjects:stu1,stu2, nil];//学生对象数组,里面包含stu1stu2


   NSData *stuData = [NSKeyedArchiver archivedDataWithRootObject:stuArray];//归档

   NSLog(@"data = %@",stuData);

   NSArray *stuArray2 =[NSKeyedUnarchiver unarchiveObjectWithData:stuData];//逆归档

   NSLog(@"array2 = %@",stuArray2);


0 0
原创粉丝点击