NSCoding是一个protocol. 如果实现了NSCoding,需要实现其中的两个方法:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder; // NS_DESIGNATED_INITIALIZER
方法中的主要的参数就是NSCoder,它是archivie字节流的抽象类.可以将数据写入一个coder,也可以从coder中读取我们写入的数据. NSCoder是一个抽象类,不能直接使用它来创建对象. 但是可以通过其子类NSKeyedUnarchiver从字节流中读取数据,NSKeyedArchiver将对象写入到字节流。本文以书籍为例:
新建一个Book类,Book.h中的代码:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface Book : NSObject<NSCoding>
@property (strong,nonatomic) UIImage *ConverPicture;
@property (strong,nonatomic) NSString *BookName;
@property (strong,nonatomic) NSString *Author;
@property (strong,nonatomic) NSNumber *Price;
@end
Book.m中实现NSCoding的两个方法,注意中UIImage的写法与其他有所不同:
@implementation Book
- (void)encodeWithCoder:(NSCoder *)aCoder{
//注意这里是存储的是JPG图片的调用
[aCoder encodeObject:UIImageJPEGRepresentation(self.ConverPicture,1.0)forKey:@"ConverPicture"];
[aCoder encodeObject:_BookName forKey:@"BookName"];
[aCoder encodeObject:_Author forKey:@"Author"];
[aCoder encodeObject:_Price forKey:@"Price"];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
self.ConverPicture=[UIImage imageWithData:[aDecoder decodeObjectForKey:@"ConverPicture"]];
self.BookName=[aDecoder decodeObjectForKey:@"BookName"];
self.Author=[aDecoder decodeObjectForKey:@"Author"];
self.Price=[aDecoder decodeObjectForKey:@"Price"];
return self;
}
@end
网友评论