删除所有以某个单词开头的NSUserDefaults

删除所有以某个单词开头的NSUserDefaults

问题描述:

我有没有办法在我的iPhone应用程序中遍历所有 NSUserDefault 的列表,只删除某些?

Is there a way for me to "walk" through a list of all the NSUserDefaults in my iPhone app, and only delete certain ones?

例如,我想得到所有以某个单词开头的关键名称。

For example, I'd like to get all the key names that start with a certain word.

这样的事情:

[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Dog*"];


你可以查看 dictionaryRepresentation

You can look through the dictionaryRepresentation.

这是一个使用 NSPredicate 作为通用匹配器以获得更大的灵活性。

Here's an implementation which uses NSPredicate as a generic matcher for greater flexibility.

@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];