Save custom objects in NSUserDefaults

Posted by Daniel Vela on July 4, 2011

To store objects in NSUserDefaults must use the class NSKeyedArchiver:

+(void)saveCustomObject:(NSMutableArray*)object forKey:(NSString*)key  
{  
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];  
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];  
    [prefs setObject:myEncodedObject forKey:key];  
    [[NSUserDefaults standardUserDefaults] synchronize];  
} 

+(NSMutableArray*)loadCustomObjectWithKey:(NSString*)key  
{  
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];  
    NSData *myEncodedObject = [prefs objectForKey:key ];  
    NSMutableArray *obj = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];  
    return obj;  
}