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.

//NSUserDefaults_RCastr.h
@interface NSUserDefaults (RCastr)

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

//NSUserDefaults_RCastr.m
#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];
}

@end

That allows me to use user defaults like the following:


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

    //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:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s