Create a Custom Class to Parse a String
I've created a method that returns a string based on values looked up from NSUserDefaults.
- (NSString *) getString:(NSInteger *)intID {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *strMyString;
if ((int)intID == 1) {
strMyString = [userDefaults stringForKey:kSomeStuff];
} else {
strMyString = [userDefaults stringForKey:kSomeOtherStuff];
开发者_Go百科 }
// ... do a bunch of string parsing
return strMyString;
}
Works great. Except I have this method duplicated in a half dozen different view controllers classes. It seems like the perfect case for a custom class that can be shared by all the various view controllers. But I have no idea how to do that. Any help is appreciated! lq
This would be a perfect use of a category on NSUserDefaults
. Then you could have methods like this:
- (NSString *)someStuff {
return [self stringForKey:kSomeStuff];
}
- (NSString *)someOtherStuff {
return [self stringForKey:kSomeOtherStuff];
}
Then, when you need these values, you just write:
[[NSUserDefaults standardUserDefaults] someStuff];
A simple solution is to add a class that inherits from NSObject
(named "StringMangler" or whatever), and put your (hopefully) stateless convenience method there as a static method:
+ (NSString *) getString:(NSInteger *)intID {
In your view controllers, #import "StringMangler.h"
and then call
[StringMangler getString:myID];
Create a custom class and name it UserDefaultsHelper for example. Put all the code you wrote you to handle read and writing to NSUserDefaults. Then just use this custom in all your controllers when you need to access that information. This way if you need to make changes, you have only one place to look.
a function is all you need:
NSString * MONIdentifiedStringForID(NSInteger intID) {
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
NSString * s = nil;
if (intID == 1) {
s = [userDefaults stringForKey:kSomeStuff];
}
else {
s = [userDefaults stringForKey:kSomeOtherStuff];
}
assert(s);
/* ... do a bunch of string parsing */
return s;
}
if your classes have no relation, then you may simply wrap it as/if needed:
- (NSString *)getString:(NSInteger)intID {
return MONIdentifiedStringForID(intID);
}
精彩评论