我尝试使用NSKeyedArchiver和NSKeyedUnarchiver。代码抛出异常:“[NSConcreteValue length]:无法识别的选择器发送到实例”。
@interface DBTLine() <NSCoding>
@end
@implementation DBTLine
-(void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeCGPoint:self.begin forKey:@"begin"];
[aCoder encodeCGPoint:self.end forKey:@"end"];
[aCoder encodeObject:self.color forKey:@"color"];
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
//Throw Exception Here.
_begin = [coder decodeCGPointForKey:@"begin"];
_end = [coder decodeCGPointForKey:@"end"];
_color = [coder decodeObjectForKey:@"color"];
}
return self;
}
@end
@interface DBTDrawView()
@property (nonatomic)NSMutableArray *finishedLines;
@end
@implementation DBTDrawView
-(instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self){
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData* dataFinishedLines = [defaults objectForKey:@"finishedLines"];
NSMutableArray *defaultLines = [NSKeyedUnarchiver unarchiveObjectWithData:dataFinishedLines];
if (defaultLines) {
self.finishedLines = defaultLines;
}
}
return self;
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//some code,"self.finishedLines" add line
NSData *dataFinishedLines = [NSKeyedArchiver archivedDataWithRootObject:self.finishedLines];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:dataFinishedLines forKey:@"finishedLines"];
[self setNeedsDisplay];
}
@end
我在互联网上搜索了很长时间,我尝试了多种代码。最后,它有效。这是我改变的代码:
-(void)encodeWithCoder:(NSCoder *)aCoder {
NSValue *begin = [NSValue valueWithCGPoint:self.begin];
NSValue *end = [NSValue valueWithCGPoint:self.end];
[aCoder encodeObject:begin forKey:@"begin"];
[aCoder encodeObject:end forKey:@"end"];
[aCoder encodeObject:self.color forKey:@"color"];
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
NSValue *begin = [coder decodeObjectForKey:@"begin"];
NSValue *end = [coder decodeObjectForKey:@"end"];
_begin = [begin CGPointValue];
_end = [end CGPointValue];
_color = [coder decodeObjectForKey:@"color"];
}
return self;
}
但问题是:
提前致谢。