-(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.
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.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With