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!
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.
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.
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.
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.
UserDefaults
is one kind of key value pair persistent store. To solve your problem you have to follow the steps:
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];
}
}
Swift 5 is the same as Swift 4
for key in UserDefaults.standard.dictionaryRepresentation().keys {
if key.hasPrefix("NavView") {
UserDefaults.standard.removeObject(forKey: key)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With