6

I want to remove strings that are stored in the NSUserDefaults for the keys beginning with "NavView".
I thought about using the hasPrefix() method, but I just can't seem to figure it out.

I know that other programming languages have features like taking every string with a certain beginning by passing the prefix they want it to have like: find all strings with "NavView*" or something. (using signs like the star to indicate that)

Any ideas how I could do that except storing all the objects in an array and saving that?
Thanks in advance!

LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174

3 Answers3

15

UserDefaults is one kind of key value pair persistent store. To solve your problem you have to follow the steps:

  • Iterate over the all keys of UserDefaults Dictionary.
  • Check each key has prefix "NavView".
  • If key has the prefix then remove the object for the key.

Swift 4:

for key in UserDefaults.standard.dictionaryRepresentation().keys {
    if key.hasPrefix("NavView"){
        UserDefaults.standard.removeObject(forKey: key)
    }
}

Objective C :

NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];

for (NSString *key in [userDef dictionaryRepresentation].allKeys) {
    if ([key hasPrefix:@"start"]) {
        [userDef removeObjectForKey:key];
    }
}
Muzahid
  • 5,072
  • 2
  • 24
  • 42
1

Swift 5 is the same as Swift 4

for key in UserDefaults.standard.dictionaryRepresentation().keys {
            if key.hasPrefix("NavView") {
                UserDefaults.standard.removeObject(forKey: key)
            }
        }
Zgpeace
  • 3,927
  • 33
  • 31
0

You can get all the keys and filter only the ones that start with the prefix. See example - Delete all my NSUserDefaults that start with a certain word

Community
  • 1
  • 1
little
  • 2,927
  • 2
  • 25
  • 36