Search code examples
iosswiftsavensuserdefaults

Remove NSUserDefaults for keys starting with


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!


Solution

  • 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];
        }
    }