Quick one guys. I’m trying to force my self to write one blog each day, but.. Today is champions league and I’m tired and … yeah 🙂 So this is gonna be a short one.
Problem: Managing reference to objects in NSUserDefaults and Arrays trough strings.
Description: I was delighted to learn how easy it is to store data in iOS. What I didn’t like was hard-coded strings. Here’s an example how to set variable money in a NSUserDefaults under key “allMoney”:
- (void)resetAllMoney { NSNumber* money = [NSNumber numberWithDouble:0]; NSUserDefaults* repository = [NSUserDefaults standardUserDefaults]; [repository setObject:money forKey:@"allMoney"]; [repository synchronize]; [[NSNotificationCenter defaultCenter] postNotificationName:@"msgMoneySaved" object:nil]; }
So here’s my nifty solution:
I created a .h file that is basically empty and in it I define all my strings. I just include .h file in classes that use NSUserDetails and Arrays. Here’s an example of my .h file:
#import #define myNsDefaultsPayCheckAmount @"initParamPayCheck" #define myNsDefaultsWorkHoursAmount @"initParamWorkHours" #define myNsDefaultsPayCheckType @"initParamPayCheckType" #define myNsDefaultsWorkHoursType @"initParamWorkHourType" #define myNsDefaultsCurrencyType @"initParamCurrencyType" #define myNsDefaultsAllMoney @"allMoney" @interface MyStrings : NSObject {} @end
And now when we include MyString.h in any class we can easily use it like:
[repository setObject:money forKey:myNsDefaultsAllMoney];
One other kind of interesting thing happened while I was refactoring my code. I noticed that I had to change a lot of classes just to adjust to new “string managing” system. I didn’t smell right so I decided to crate a light weight data layer. After that air was nice and fresh, day was brighter and I could swear birds sang better 🙂
You might also consider simple string constants:
static NSString *const myString = @”whatever”;
If you want to hide the implementation you can do the following:
.h file:
extern NSString *const myString;
.m file
NSString *const myString = @”whatever”