Naveed Rafi
Naveed Rafi

Reputation: 2643

Saving inherited objects in NSUserDefaults

I am using a class which is being inherited from NSObject that is 'userDC'. This object is being saved in user defaults properly without any issue.
But now I have created one more class which is being inherited from userDC that is called 'appUserDC'.
When I try to save data in appUserDC and it's parent object it is being saved properly but when I try to save it in archive and try to retrieve it back it does not return any data which was being saved in userDC properties.

Any help is appreciated.

Thanks.

Upvotes: 1

Views: 247

Answers (1)

rishi
rishi

Reputation: 11839

While creating your object class using NSCopying protocol methods - initWithCoder: and encodeWithCoder:

From the class where you want to save the object use - archivedDataWithRootObject method of NSKeyedArchiver, this will return Data object.

After Retrieving the object, you have to unarchive that - unarchiveObjectWithData method of NSKeyedUnarchiver.

Objective C example -

Class AppuserDC

in the implementation .m file-

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.myProperty forKey:@"myProperty"];
}

- (id)initWithCoder:(NSCoder *)decoder
{
    if((self = [super initWithCoder:decoder]))
    {
        self. myProperty = [decoder decodeObjectForKey:@"myProperty"];
    }
    return self;
}

While saving your object -

- (void)saveMyObject:(AppuserDC *)user
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:user];
    [defaults setObject:myEncodedObject forKey:@"user"];
    [defaults synchronize];
}

And retrieving object -

- (id)loadUserObject
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [defaults objectForKey:@"user"];

    id obj = [NSKeyedUnarchiver unarchiveObjectWithData:myEncodedObject];
    return obj;
}

Upvotes: 1

Related Questions