NSUserDefaults encodeWithCoder unrecognized selector sent to instance

1.4k views Asked by At

I want to save NSMutableDictionary to NSUserDefaults then get error:

NSUserDefaults encodeWithCoder unrecognized selector sent to instance. Fatal Exception: NSInvalidArgumentException [NSUserDefaults encodeWithCoder:]: unrecognized selector sent to instance 0x17544a080

Here is my code:

NSUserDefaults *shared2 = [[NSUserDefaults alloc]initWithSuiteName:@"AppGroupName"];
NSMutableData *data1 = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data1];
[archiver encodeObject:shareDic forKey: @"shareDic"];
[archiver finishEncoding];

if (data1 !=nil)
{
    [shared2 setObject:data1 forKey:@"dicFitnessData"];
}
1

There are 1 answers

1
Ankur On

You need to implement the nscoding protocol.

    - (void)encodeWithCoder:(NSCoder *)aCoder{
      [aCoder encodeObject:self.yourpoperty forKey:@"Your_KEY"];
      }

    - (id)initWithCoder:(NSCoder *)aDecoder{
       if(self = [super init]){
         self.yourpoperty = [aDecoder decodeObjectForKey:@"Your_KEY"];
        }
        return self;
      }