创建自定义类来解析字符串
我创建了一个方法,该方法根据从 NSUserDefaults 查找的值返回一个字符串。
- (NSString *) getString:(NSInteger *)intID {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *strMyString;
if ((int)intID == 1) {
strMyString = [userDefaults stringForKey:kSomeStuff];
} else {
strMyString = [userDefaults stringForKey:kSomeOtherStuff];
}
// ... do a bunch of string parsing
return strMyString;
}
效果很好。除了我在六个不同的视图控制器类中重复了这个方法。这似乎是自定义类的完美案例,可以由所有不同的视图控制器共享。但我不知道该怎么做。 任何帮助表示赞赏! lq
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];
}
// ... 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这将是
NSUserDefaults
上的类别。然后你可以有这样的方法:然后,当你需要这些值时,你只需编写:
This would be a perfect use of a category on
NSUserDefaults
. Then you could have methods like this:Then, when you need these values, you just write:
一个简单的解决方案是添加一个继承自
NSObject
的类(名为“StringMangler”或其他名称),并将您的(希望)无状态便捷方法作为静态方法放在那里:在您的视图控制器中,
#import "StringMangler.h"
然后调用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:In your view controllers,
#import "StringMangler.h"
and then call例如,创建一个自定义类并将其命名为 UserDefaultsHelper。将您编写的用于处理读取和写入的所有代码放入 NSUserDefaults 中。然后,当您需要访问该信息时,只需在所有控制器中使用此自定义即可。这样,如果您需要进行更改,您只需查看一个地方。
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:
if your classes have no relation, then you may simply wrap it as/if needed: