Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrecognized selector sent to instance while archiving data (NSCoding)

Tags:

-(void)transformObjects:(NSMutableArray*)array key:(NSString*)key {     NSMutableArray* archiveArray = [[NSMutableArray alloc]initWithCapacity:array.count];      for (Furniture *furniture in array) {          // The error occurs on the line below         NSData *furnitureEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:furniture];         [archiveArray addObject:furnitureEncodedObject];     }      NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];     [userData setObject:archiveArray forKey:key]; } 

Error log:

2014-03-04 10:55:27.881 AppName[10641:60b] -[Furniture encodeWithCoder:]: unrecognized selector sent to instance 0x15d43350 

I have no idea why do I get "unrecognized selector sent to instance" when trying to archive an object.

like image 286
SteBra Avatar asked Mar 04 '14 10:03

SteBra


2 Answers

You need to implement NSCoding protocol inside your Furniture object:

- (void)encodeWithCoder:(NSCoder *)aCoder{   [aCoder encodeObject:self.yourpoperty forKey:@"PROPERTY_KEY"]; }  -(id)initWithCoder:(NSCoder *)aDecoder{   if(self = [super init]){     self.yourpoperty = [aDecoder decodeObjectForKey:@"PROPERTY_KEY"];   }   return self; } 

Basically you specify what should be written (encoded) and read from a file (decoded). Usually for each property you want to store in a file, you make same as I did here in an example.

like image 110
Grzegorz Krukowski Avatar answered Oct 05 '22 23:10

Grzegorz Krukowski


You'll need to implement NSCoding - here is an example with an object called SNStock that has two string properties, ticker and name:

import Foundation  class SNStock: NSObject, NSCoding {   let ticker: NSString   let name: NSString    init(ticker: NSString, name: NSString)   {     self.ticker = ticker     self.name = name   }    //MARK: NSCoding    required init(coder aDecoder: NSCoder) {     self.ticker = aDecoder.decodeObjectForKey("ticker") as! NSString     self.name = aDecoder.decodeObjectForKey("name") as! NSString   }    func encodeWithCoder(aCoder: NSCoder) {     aCoder.encodeObject(ticker, forKey: "ticker")     aCoder.encodeObject(name, forKey: "name")   }    //MARK: NSObjectProtocol    override func isEqual(object: AnyObject?) -> Bool {     if let object = object as? SNStock {       return self.ticker == object.ticker &&         self.name == object.name     } else {       return false     }   }    override var hash: Int {     return ticker.hashValue   } } 
like image 23
Zorayr Avatar answered Oct 06 '22 00:10

Zorayr