-3

I have an array of object (custom object), it's called "favorite" and when I try to store this array in NSUserDefault i have this error

my code:

inside favorite -> (object1, object2, object3...) from class MyObject

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData* myClassArrayData = [NSKeyedArchiver archivedDataWithRootObject:favorite];
    [defaults setObject:myClassArrayData forKey:@"favorite"];

my error:

[MyObject encodeWithCoder:]: unrecognized selector sent to instance

why?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
cyclingIsBetter
  • 17,447
  • 50
  • 156
  • 241
  • 1
    http://stackoverflow.com/questions/4317164/save-own-class-with-nscoder http://stackoverflow.com/questions/1659922/converting-a-nsobject-into-nsdata – maroux Jun 06 '13 at 14:10

1 Answers1

4

To store custom object, MyObject in your case, the class must implement the NSCoder interface.

The interface only has two methods:

- (id) initWithCoder:(NSCoder *)aDecoder {
    self = [super init];

    if (self) {

        self.identifier = [aDecoder decodeIntegerForKey:@"identifier"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
        /* continue with all the properties that need to be restored  */

    }

    return self;
}

- (void) encodeWithCoder:(NSCoder *)aCoder {
     [aCoder encodeInteger:self.identifier forKey:@"identifier"];
     [aCoder encodeObject:self.name forKey:@"name"];
     /* continue with all the properties that need to be saved  */
}
rckoenes
  • 69,092
  • 8
  • 134
  • 166
  • that's a compilation issue. It wouldn't cause a unrecognized selector sent to instance error at runtime – Max MacLeod Jun 06 '13 at 14:12
  • 2
    In the error it is stated that `MyObject` does not recognize `encodeWithCoder:` which is one of the two methods you will need to implement to make you class conform the the `NSCoder` interface. – rckoenes Jun 06 '13 at 14:13
  • yes, you need to provide the methods. Whether or not you specify that your object conforms to the protocol only matters at compilation. – Max MacLeod Jun 06 '13 at 14:21
  • True, but the error clearly states that the class `MyObject` does not. So either the `favorite` variable is of type `MyObject` or it contains a property of type `MyObject` which it is trying to encode. Either way the `MyObject` class does not comply to the `NSCoder` interface. – rckoenes Jun 06 '13 at 14:30
  • Yes, its working fine for me. First i wrongly implement these two methods in viewcontroller. Later i realize that implement in NSObject class. Thank you. – Mahesh_P Mar 13 '14 at 06:27