Is there a way for me to "walk" through a list of all the NSUserDefault
s 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*"];
In the simulator top menu: Simulator -> Reset Content and Settings... Show activity on this post. You can use removePersistentDomainForName method available with NSUserDefaults Class.
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.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With