Delete all my NSUserDefaults that start with a certain word

删除回忆录丶 提交于 2019-12-18 16:25:32

问题


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.

Something like this:

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

回答1:


You can look through the dictionaryRepresentation.

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

Usage:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", @"something"];
[[NSUserDefaults standardUserDefaults] removeObjectsWithKeysMatchingPredicate:pred];



回答2:


i Got solution for this just use it where you want to remove all sessions

 NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

it will work



来源:https://stackoverflow.com/questions/3436792/delete-all-my-nsuserdefaults-that-start-with-a-certain-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!