Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all my NSUserDefaults that start with a certain word

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*"];
like image 482
Patricia Avatar asked Aug 09 '10 01:08

Patricia


People also ask

How do you reset NSUserDefaults?

In the simulator top menu: Simulator -> Reset Content and Settings... Show activity on this post. You can use removePersistentDomainForName method available with NSUserDefaults Class.

What is NSUserDefault?

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user's preferences. For example, you can allow users to specify their preferred units of measurement or media playback speed.

Which method is used to remove all keys from user default?

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

How do you check if NSUserDefaults is empty in Objective C?

There isn't a way to check whether an object within NSUserDefaults is empty or not. However, you can check whether a value for particular key is nil or not.


1 Answers

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];
like image 162
Jacob Relkin Avatar answered Nov 07 '22 06:11

Jacob Relkin