Search code examples
objective-cnscoder

NScoder objective-c run time


NSCoder *coder; 
coder=[[NSCoder alloc]init];
[coder encodeObject:@"value" forKey:@"frame"];

Error

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -encodeObject:forKey: cannot be sent to an abstract object of class NSCoder: Create a concrete instance!`


this breaks during run time.can any body help me to find it what i am doing wrong?


Solution

  • Need to create a model class, and in this model class, need to implement a NSCodingProtocol

    e.g Book Class

    Book.h
    
    @interface Book : NSObject<NSCoding>
    
    @property (nonatomic, retain) NSString *name;
    @property (nonatomic, retain) NSString *author;
    
    @end
    
    Book.m
    
    - (id)initWithCoder:(NSCoder *)aDecoder {
        if (self = [super init]) {
            self.title = [aDecoder decodeObjectForKey:@"name"];
            self.author = [aDecoder decodeObjectForKey:@author"];
        }
        return self;
    }
    
    - (void)encodeWithCoder:(NSCoder *)aCoder {
        [aCoder encodeObject:_name forKey:@"name"];
        [aCoder encodeObject:_author forKey:@"author"];
    }