2010-08-09 85 views
7

有沒有辦法讓我在我的iPhone應用程序中「遍歷」所有NSUserDefault的列表,並且只刪除某些列表?刪除所有以某個詞開始的我的NSUserDefaults

例如,我想要獲取以某個單詞開頭的所有關鍵名稱。

事情是這樣的:

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

回答

18

你可以去翻dictionaryRepresentation

這是一個實現,它使用NSPredicate作爲通用匹配器以獲得更大的靈活性。

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

我得到了這個解決方案要刪除所有會話

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

只是用它,將工作

相關問題