删除所有以某个单词开头的NSUserDefaults [英] Delete all my NSUserDefaults that start with a certain word

查看:110
本文介绍了删除所有以某个单词开头的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];

这篇关于删除所有以某个单词开头的NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆