使用NSKeyedArchiver抛出异常:[NSConcreteValue length]:发送到实例的无法识别的选择器

时间:2017-01-22 16:04:49

标签: ios objective-c

我尝试使用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;
}

但问题是:

  1. 似乎问题出现在使用“ -
    encodeCGPoint:forKey: - decodeCGPointForKey:“。有没有什么东西 我做了什么错了?
  2. 什么是“[NSConcreteValue length]”?我在文档中找不到它。
  3. 提前致谢。

0 个答案:

没有答案