Encoding and decoding custom objects in NSUserDefaults



In this post, I will show you how to save and load custom objects in NSUserDefaults, with two very simple and short methods using NSKeyedArchiver and NSKeyedUnArchiver.

Encode custom object:

+(void)saveCustomObject:(id)object key:(NSString *)key{
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    if (encodedObject) {
        [[NSUserDefaults standardUserDefaults] setObject:encodedObject forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];


Decode custom object:

+(id)loadCustomObjectWithKey:(NSString *)key{
    NSData *encodedObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if (encodedObject){
        id decodeObj = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
        return decodeObj;
    return nil;


Leave a Reply

Your email address will not be published. Required fields are marked *