Simplified NSUserDefaults

I use NSUserDefaults all the time for storing simple users settings and application state.  But there’s a whole lotta string literals and a bunch of repeating yourself that takes place.  That sucks ….

So I like to create a category on NSUserDefaults so I can treat it like a concrete class, whose API is enforced by the compiler and autocompleted by Xcode.  Here’s an example of how I use it to track a users email address within my app.  Note the rcast_ prefix.  Always a good idea to prefix your categories to prevent future name collisions.

@interface NSUserDefaults (RCastr)

@property (assign, getter=rcast_userEmail,
           setter=rcast_setUserEmail:) NSString *rcast_userEmail;

#import "NSUserDefaults+RCastr.h"
NSString *const rcastDefaultsKeyUserEmail = @"rcast_userEmail";

@implementation NSUserDefaults (RCastr)

#pragma mark -
#pragma mark Username

- (NSString *)rcast_userEmail {
    return [self stringForKey:rcastDefaultsKeyUserEmail];

- (void)rcast_setUserEmail:(NSString *)userEmail {
    [self setObject:userEmail forKey:rcastDefaultsKeyUserEmail];
    [self synchronize];


That allows me to use user defaults like the following:

    //Set the email address
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    defaults.rcast_userEmail = @"";

    //Get the email address
       NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (defaults.rcast_userEmail){
        [FlurryAnalytics setUserID:defaults.rcast_userEmail];

Dead easy change, but much cleaner and far less error prone.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s