有没有办法让我“遍历”我的 iPhone 应用程序中所有 NSUserDefault
的列表,并且只删除某些?
例如,我想获取所有以某个单词开头的键名。
像这样:
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Dog*"];
最佳答案
可以翻看dictionaryRepresentation
.
这是一个使用 NSPredicate
的实现作为通用匹配器以获得更大的灵 active 。
@interface NSUserDefaults (JRAdditions)
- (void)removeObjectsWithKeysMatchingPredicate:(NSPredicate *)predicate;
@end
@implementation NSUserDefaults (JRAdditions)
- (void)removeObjectsWithKeysMatchingPredicate:(NSPredicate *)predicate {
NSArray *keys = [[self dictionaryRepresentation] allKeys];
for(NSString *key in keys) {
if([predicate evaluateWithObject:key]) {
[self removeObjectForKey:key];
}
}
}
@end
用法:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", @"something"];
[[NSUserDefaults standardUserDefaults] removeObjectsWithKeysMatchingPredicate:pred];
关于iphone - 删除以某个单词开头的所有 NSUserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3436792/