ios 数据归档问题
请教一个问题:
我们把数据归档的时候,CGPoint类可以直接归档吗?还有那些自定义的绘图类含有image也可以归档吗,怎么归档存储。
[解决办法]
你是问CGPoint与UIImage的归档吧,刚才写了个demo都可以啊。
1)自定义的类里面继承NSCoding 与NSCopying,你的point就定义成NSValue。
@property (copy,nonatomic) UIImage *image;
@property (copy,nonatomic) NSValue *point;
2)归档的时候就用encodeObject
[encoder encodeObject:image forKey:@”ImageKey”];
[encoder encodeObject:point forKey:@”PointKey”];
3)存的时候
CGPoint point = CGPointMake(1.1, 2.2);
NSValue *value = [NSValue valueWithCGPoint:point];
//存储数据到类
Archive *archivingData = [[Archive alloc] init];
archivingData.image = [UIImage imageNamed:@"pic.jpg"];
archivingData.point = value;
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:archivingData forKey: @"ArchivingData"];
[archiver finishEncoding];
//写入文件
[data writeToFile:self.archivingFileRootPath atomically:YES];// archivingFileRootPath就是存的路径
4)取得时候
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:self. archivingFileRootPath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//获得类
Archive *archivingData = [unarchiver decodeObjectForKey: @"ArchivingData"];
[unarchiver finishDecoding];
self.imageView.image = archivingData.image;
NSValue *value = archivingData.point;
CGPoint point = [value CGPointValue];
NSLog(@"%f
[解决办法]
%f",point.x,point.y);
当然如果你是做游戏的话,建议你把那些CGPoint都放到NSArray里面吧(转化为NSValue)