Nsuserdefaults remove value and key - swift

I want to know how to remove both key and value in NSUserDefaults . removeobjectforkey only removes the value ?
removeObjectForKey(string)

Swift 3
to add value in NSUserDefault
integer
UserDefaults.standard.integer(forKey: "key")
a dictionary
UserDefaults.standard.set(Dictvariable, forKey: "key")
get value
from integer
key value = UserDefaults.standard.integer(forKey: "key")
get value from dictionary
let result = UserDefaults.standard.value(forKey: "key") as? [String: String] ?? [String: String]()
to remove(i not tried this u can try this take it from stackoverflow 99% its work)
UserDefaults.standard.removeObject(forKey: "yourKey")

Related

Not able to access data from Userdefaults - Swfit

I am accessing user default value as:
let data = UserDefaults.standard.object(forKey: identifier)
when I see the value in data it is visible as:
https://i.stack.imgur.com/UOjI8.png
type of data is
po type(of: data)
Swift.Optional<Any> . //Output
How can I access pageNumber?
since data is a dictionary in order to have access to pageNumber you need to cast data as a Dictionary
guard let data = UserDefaults.standard.value(forKey: identifier) as? [String: Any] else { //fallback here if you need return }
let pageNumber = data["pageNumber"] as? Int ?? 0
Simply use dictionary(forKey:) method on UserDefaults instance to directly fetch a dictionary from UserDefaults.
The dictionary returned is of type [String:Any]?
if let dict = UserDefaults.standard.dictionary(forKey: identifier) {
let pageNumber = dict["pageNumber"] as? Int
}
Note: pageNumber is of type Int?. Unwrap it to use further.

Store dictionary with optional values [String: AnyObject?] in NSUserDefaults

I need to store a dictionary that which can contain a nil as a value
Example
var someOptionalVar: String? = nil
var dict: [String: AnyObject?] = [
"someOptionalVar": self.someOptionalVar
]
defaults.setObject(dict, forKey: self.nsUserDefaultsKey)
But it gives me this error
Cannot convert value of type '[String: AnyObject?]' to expected
argument type 'AnyObject?'
I know I could leave the nil variables and then when I'm parsing the dictionary from NSUserDefaults I would set variables (corresponding to the missing properties) to nil, but this is not what I would like to do.
So how can I store nil values in NSUserDefaults ?
Use NSNull() instead of nil, and declare the dictionary to contain only non-optionals:
var someOptionalVar: String? = nil
var dict: [String: AnyObject] = [
"someOptionalVar": self.someOptionalVar ?? NSNull()
]
defaults.setObject(dict, forKey: self.nsUserDefaultsKey)

Cannot get the dictionary from NSUserDefaults as saved format

I want to get a swift dictionary from NSUserDefaults as the format that I've saved before. I've saved the dictionary as [String:String] format, but while I'm getting the dictionary with dictionaryForKey(key) method I got [String:AnyObject]?. How can I convert [String:AnyObject]? to [String:String] or how can I get the dictionary in right format?
Saving to NSUserDefaults
var tasks: Dictionary<String,String> = [:]
let defaults = NSUserDefaults.standardUserDefaults()
let key = "key"
defaults.setObject(tasks, forKey: key)
defaults.synchronize()
Getting from NSUserDefaults
let defaults = NSUserDefaults.standardUserDefaults()
let key = "ananZaa"
let incomingArray = defaults.dictionaryForKey(key)
If you've registered it with a default value so it never can be nil, just downcast it to the proper type
let defaults = NSUserDefaults.standardUserDefaults()
let key = "ananZaa"
let incomingDictionary = defaults.objectForKey(key) as! Dictionary<String,String>

NSMutableDictionary: Cast to unrelated Swift type?

Can anyone help me out with the correct way round this, I have tried various versions but always hit either an error or a warning. The code and output below are from a Swift Playground.
var foundationDict = NSMutableDictionary()
foundationDict.setObject("Bilbo", forKey: "FirstName")
foundationDict.setObject("Baggins", forKey: "LastName")
var swiftDict = foundationDict as! Dictionary<String, String>
for (key, value) in swiftDict {
print("KEY: \(key) VALUE: |\(value)")
}
OUTPUT:
KEY: FirstName VALUE: |Bilbo
KEY: LastName VALUE: |Baggins
WARNING:
Cast from NSMutableDictionary to unrelated type Dictionary<String String> always fails
I'm not sure why, but phrasing it this way silences the warning:
var swiftDict = (foundationDict as NSDictionary) as! Dictionary<String, String>
The type system seems to struggle with NSMutableDictionary/NSDictionary in this case.
A correct version of your code is:
var foundationDict = NSMutableDictionary()
foundationDict.setObject("Bilbo", forKey: "FirstName")
foundationDict.setObject("Baggins", forKey: "LastName")
for (key, value) in foundationDict {
println("KEY: \(key) VALUE: |\(value)")
}
There is no need in casting because NSDictionary is bridged to swift Dictionary and foundationDict is now a swift mutableDict.
without warning you can follow this way
var addressDict = NSMutableDictionary()
addressDict["key"] = "value"
if let dict = (addressDict as NSDictionary) as? [String:AnyObject] {
print(dict)
}

saving key and value pairs swift

I need a way to save key and value pairs in swift for my application. I am new to IOS programming, but I know Android and I am looking for something like shared preferences in android, but for swift. By "save," I mean that when the user quits out of the application, the key and value pairs are saved in the local data.
Swift 3.0
Saving Data:
let userDefaults = UserDefaults.standard
userDefaults.set(yourKey, forKey: "yourKey")
userDefaults.synchronize()
Reading Data:
if let yourVariable: AnyObject = UserDefaults.standard.object(forKey: "yourKey") as AnyObject? { }
What you are looking for is called "Userdefaults" - you can use them like this:
Saving Data:
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(variable, forKey: "yourKey")
userDefaults.synchronize()
Reading Data:
if let yourVariable: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") {
....
Here you find more information:
https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html
Working way for Swift 3+:
// Storing values
UserDefaults.standard.set(true, forKey: "KeyName") // Bool
UserDefaults.standard.set(1, forKey: "KeyName") // Integer
UserDefaults.standard.set("TEST", forKey: "KeyName") // setObject
// Retrieving values
UserDefaults.standard.bool(forKey: "KeyName")
UserDefaults.standard.integer(forKey: "KeyName")
UserDefaults.standard.string(forKey: "KeyName")
// Removing values
UserDefaults.standard.removeObject(forKey: "KeyName")