Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 242
LinusGeffarth Avatar asked Mar 20 '16 07:03

LinusGeffarth


People also ask

How do I remove a default user?

To remove a key-value pair from the user's defaults database, you need to invoke removeObject(forKey:) on the UserDefaults instance. Let's update the previous example. The output in the console confirms that the removeObject(forKey:) method works as advertised.

What is NSUserDefaults?

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.

How much data can you store in NSUserDefaults?

It appears the limit is the maximum file size for iOS (logically), which is currently 4GB: https://discussions.apple.com/thread/1763096?tstart=0. The precise size of the data is circumscribed by the compiler types (NSData, NSString, etc.) or the files in your asset bundle.

How do you check if NSUserDefaults is empty in Objective C?

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.


2 Answers

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];
    }
}
like image 108
Muzahid Avatar answered Nov 14 '22 22:11

Muzahid


Swift 5 is the same as Swift 4

for key in UserDefaults.standard.dictionaryRepresentation().keys {
            if key.hasPrefix("NavView") {
                UserDefaults.standard.removeObject(forKey: key)
            }
        }
like image 36
Zgpeace Avatar answered Nov 15 '22 00:11

Zgpeace