简体   繁体   中英

find special keys in UserDefaults by “substringToIndex”

I'm grouping my UserDefault keys by specific prefixes.

eg

[NSUserDefaults standardUserDefaults] setInteger: 1 forKey: @"prefix1_someText_Key"]
[NSUserDefaults standardUserDefaults] setInteger: 2 forKey: @"prefix2_someText_Key"]
[NSUserDefaults standardUserDefaults] setInteger: 3 forKey: @"prefix4_someText_Key"]
//.....

Now, I'd like to find all the keys, that start with eg "prefix", and load them into an array. is there a way for doing that (programmatically)?

You could use the underlying NSDictionary to find the suitable keys:

NSString *myPrefix = @"prefix";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [defaults dictionaryRepresentation];
NSMutableArray *keysWithPrefix = [NSMutableArray array]
for (NSString *key in dict.keyEnumerator) {
  if ([key hasPrefix: myPrefix]) {
    [keysWithPrefix addObject: key];
  }
}
// now keysWithPrefix contains all matching keys

UPDATE For debugging reasons you could add a log to see what keys are being dropped:

for (NSString *key in dict.keyEnumerator) {
  if ([key hasPrefix: myPrefix]) {
    [keysWithPrefix addObject: key];
  } else {
    NSLog(@"Dropping key %@", key);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM