How to remove mutable array element from NSUserdefaults? - ios

I store array element in NSUserdefault and retrive from this but I want to remove array element from NSUserdefault.
retriving from NSuserdefault
let defaults = UserDefaults.standard
let array = defaults.object(forKey: "ArrayString") as? [String] ?? [String]()
print("NSUserDefault :\(array)")
Result:
NSUserDefault :["first", "second","third","fourth","fifth"]
I display this array in CollectionView now I want to remove from this array how?
Thank You in Advance..

We can remove element from NSUserdefault see this...
---> Self Solution and Helpful for me...
Store array in NSUserdefault
let defaults = UserDefaults.standard
defaults.set(appDelegate.arrMutable, forKey: "ArrayString")
defaults.synchronize()
Retrieving from NSUserdefault
var array : Array<String> = []
array = defaults.object(forKey: "ArrayString") as? [String] ?? [String]()
Remove array element from NSUserdefault
array.remove(at: buttonIndex)
defaults.set(array, forKey: "SavedStringArray")
defaults.synchronize()
print("Removed Array:\(array)")

Swift 2.x
NSUserDefaults.standardUserDefaults().removeObjectForKey("MyKey")
Swift 3.0
UserDefaults.standard.removeObject(forKey: "MyKey")

You just need to delete item from array and then again save the same array in UserDefaults, under the same key. It will overwrite original.
This is example from tableView:
itemArray.remove(at: indexPath.row)
UserDefaults.standard.set(itemArray, forKey: "itemArray")

Related

UserDefaults return 0 elements when call in awakeFromNib

I have an UICollectionView inside UITableViewCell and I'm using UserDefaults to save an array of the selected item in didSelectItem function to keep selected state after dismissing the parent view controller of them:
var arrSelectedIndex = [IndexPath]()
let encodedData = NSKeyedArchiver.archivedData(withRootObject: arrSelectedIndex)
UserDefaults.standard.set(encodedData, forKey: "arrayOfSelectedItem")
UserDefaults.standard.synchronize()
And whenever I show up the view controller I set my array with UserDefaults again in awakeFromNib:
arrSelectedIndex = UserDefaults.standard.array(forKey: "arrayOfSelectedItem") as? [IndexPath] ?? [IndexPath]()
But both my array and the UserDefaults return 0 elements (I tried to print out value of arrSelectedIndex and UserDefaults.standard.array(forKey: "arrayOfSelectedItem") as? [IndexPath] ?? [IndexPath]()) and both of them is 0 even if they have data when selected item. Does awakeFromNib reset all things inside it?
The problem is this line:
UserDefaults.standard.array(forKey: "arrayOfSelectedItem") as? [IndexPath]
That will fail, because what you saved under that key is not an array. Here is what you said earlier:
let encodedData = NSKeyedArchiver.archivedData(withRootObject: arrSelectedIndex)
UserDefaults.standard.set(encodedData, forKey: "arrayOfSelectedItem")
What you saved is encodedData. It is not an array. It is a Data. The array is encoded inside it.
First thing is to save the list in userDefault it not necessary to archive it, You can if contains basic data types.
Second, If you archive the list before saving it to UserDefault, Then You have to unarchive the encoded data to get the list.
Here is the method,
data = UserDefaults.standard.data(forKey: "arrayOfSelectedItem") as? Data
arrSelectedIndex = NSKeyedUnarchiver.unarchiveObject(with: data) as? [IndexPath] ?? [IndexPath]()
Hope this will help.
Thank you all. I have tried to unarchive before setting it to my array again and it's worked.

Can't modify array stored in NSUserDefaults

In a class FirstViewController, I add an array with key rentedItems to the NSUserDefaults in the following lines:
let itemArray = [Item]()
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(itemArray, forKey: "rentedItems")
Then, in another class SecondViewController, I try
var item: Item?
var prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
func confirmPressed() {
prefs.arrayForKey("rentedItems")?.append(item)
}
This then gives the following error:
Cannot use mutating member on immutable value: function call returns immutable value. I saw a solution in SO here that gave me an idea of the problem, but NSUserDefaults being a default iOS class, I can't use the same solution as there. Any ideas?
You can't directly modify an array from defaults. Instead make a copy, and modify that. You can save that array to defaults afterwards. Simply try like this:
var array = prefs.arrayForKey("rentedItems")?.mutableCopy
array.append(item)
You will need to archive Your Custom Object Array into NSData then save it to NSUserDefaults and retrieve it from NSUserDefaults and unarchive it again. You can archive it like this:
var userDefaults = NSUserDefaults.standardUserDefaults()
let encodedData = NSKeyedArchiver.archivedDataWithRootObject(itemArray)
userDefaults.setObject(encodedData, forKey: "rentedItems")
userDefaults.synchronize()
And unarchive it like this
let decoded = userDefaults.objectForKey("rentedItems") as! NSData
let itemArray = NSKeyedUnarchiver.unarchiveObjectWithData(decoded) as! [Item]

How to parse Object in preference with swift? [duplicate]

I am trying to store an array to NSUserDefaults and retrieve the array when needed to populate a UITableView.
Currently I am using:
//store data
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
NSUserDefaults.standardUserDefaults().synchronize()
//retrieve data
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
myArray = [tabledata!]
tableView.reloadData()
But I get
fatal error: unexpectedly found nil while unwrapping an Optional
value
when trying to load the data. I am not sure if the issue is in the storage or the retrieval. Has anyone been through this before?
From your code I see you are storing some array
// Your code
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
and retrieving a string
//Your code
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
There is probably a type mismatch, You store one type and retrieve another type.
While retrieving either use arrayForKey() or objectForKey() see the code below.
let tabledata = NSUserDefaults.standardUserDefaults().arrayForKey("\(identity.text!)listA")
or
let tabledata = NSUserDefaults.standardUserDefaults().objectForKey("\(identity.text!)listA")
If it is an array I would go with First one.
Here are the way that you can store and retrieved array of object with help of NSKeyArchive.
To Store array to NSUserDefault.
let placesData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(placesData, forKey: "places")
To Retrieved array from NSUserDefault.
let placesData = UserDefaults.standard.object(forKey: "places") as? NSData
if let placesData = placesData {
let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [Place]
print(placesArray)
}
Hope this help you.
Saving and Retrieving a String array to UserDefaults
Save array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.object(forKey: "SavedStringArray") as? [String] ?? [String]()
See more at How to save user settings using NSUserDefaults
What are you storing in the array?
If it's objects it won't work, if It's just strings or numbers then it should be fine.
Next steps you take should be to turn on exception breakpoints and maybe println() everything you can so you can pinpoint the exact whereabouts of the problem.
As a shot in the dark I would suggest maybe (identity.text!) is coming out as nil
Also you should probably change it to this
if let tabledata: NSArray = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA"){
myArray = [tabledata!]
tableView.reloadData()
}
This will make the code not even try to run unless there is a value it can use
Latest swift3 version to store array of data into userdefaults and get that array of data using keys
let nameArray = ["Ramu","JAGAN","Steve","Swift"]
let namesArrayData = NSKeyedArchiver.archivedData(withRootObject: nameArray)
UserDefaults.standard.set(namesArrayData, forKey: "arrayData")
RetriveData
let retriveArrayData= UserDefaults.standard.object(forKey: "arrayData") as? NSData
if let retriveArrayData= namesArrayData{
let retriveArray = NSKeyedUnarchiver.unarchiveObject(with: namesArraydata as Data) as? [nameArray]
print(retriveArray )
}
This has been changed in swift 3.
Note that this works with device but not playground or simulator
//store the array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.setValue(array, forKey: "history")
defaults.synchronize()
//Retrieve the array
if((UserDefaults.standard.array(forKey: "history")) != nil){
let historyWords = (UserDefaults.standard.array(forKey: "history") as? [String])!
print(historyWords)
}
Store into User Default:
let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]
//store in user default
UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")
Retrieving array from User Defaults:
if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{
print(arr)
}

How to store Array in NSUserDefault in Swift?

So I've been trying for a few hours for a way to store an array to NSUserDefault and print them to the cells but the data is not saving as an array, it basically only saves one value at a time.
var emailData = [String]()
var passwordData = [String]()
#IBAction func addPressed(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
emailData.append(addEmail.text!)
passwordData.append(addPassword.text!)
var storedEmail = defaults.objectForKey("emailData") as? [String] ?? [String]()
var storedPasswords = defaults.objectForKey("passwordData") as? [String] ?? [String]()
// then update whats in the `NSUserDefault`
defaults.setObject(emailData, forKey: "emailData")
defaults.setObject(passwordData, forKey: "passwordData")
// call this after you update
defaults.synchronize() /*
NSUserDefaults.standardUserDefaults().setValue(addEmail.text, forKey: "email")
NSUserDefaults.standardUserDefaults().synchronize()
*/
}
So basically the data is not saving.
You can store Array too, by this way
let userDefault = NSUserDefaults.standardUserDefaults()
let arr = ["abc","xyz","pqr"]
userDefault.setObject(arr, forKey: "arr")
userDefault.synchronize()
let data = userDefault.objectForKey("arr") as! [String]
Save the Swift Array in Swift.
let kUserDefault = NSUserDefaults.standardUserDefaults()
kUserDefault.setObject(["KIRIT" , "MODI" , "FIRST" , "LAST"], forKey: "nameArray")
kUserDefault.synchronize()
Get Array
1. arrayForKey : You getting Swift Array
kUserDefault.arrayForKey("nameArray")!
2. objectForKey : You getting NSArray
kUserDefault.objectForKey("nameArray")!
3. valueForKey : You getting NSArray
kUserDefault.valueForKey("nameArray")
It is possible to store arrays in NSUserDefaults. But separating email and password in separate array is not suitable. You should store it as one object since they are related.
In your case an array of Dictionary objects is better, which is possible to store in NSUserDefaults as well, which you can retrieve as an array of Dictionary.
Here is the sample:
let userDefault = NSUserDefaults.standardUserDefaults()
var storedCredentials = userDefault.objectForKey("credentials") as? [[String:AnyObject]] ?? [[String:AnyObject]]()
let email =
[
"email" : addEmail.text!,
"password": addPassword.text!
]
storedCredentials.append(email)
userDefault.setObject(storedCredentials, forKey: "credentials")
userDefault.synchronize()
You can't save an array of [String] in NSUserDefault, if you look at the documentation :
For NSArray and NSDictionary objects, their contents must be property
list objects.
So what you can do is convert your [String] into NSData then save it into NSUserDefault.
// Store it as NSData
var emailData = [String]()
emailData.append("email1")
emailData.append("email2")
let emailIntoNSData = NSKeyedArchiver.archivedDataWithRootObject(emailData)
NSUserDefaults.standardUserDefaults().setObject(emailIntoNSData, forKey: "emailData")
// Retrieve it :
let emailFromNSData = NSUserDefaults.standardUserDefaults().objectForKey("emailData") as? NSData
if let emailFromNSData = emailFromNSData {
let emailArray = NSKeyedUnarchiver.unarchiveObjectWithData(emailFromNSData) as? [String]
if let emailArray = emailArray {
NSLog("Email Data : \(emailArray)") // ["email1","email2"]
// do something…
}
}

(Swift) Storing and retrieving Array to NSUserDefaults

I am trying to store an array to NSUserDefaults and retrieve the array when needed to populate a UITableView.
Currently I am using:
//store data
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
NSUserDefaults.standardUserDefaults().synchronize()
//retrieve data
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
myArray = [tabledata!]
tableView.reloadData()
But I get
fatal error: unexpectedly found nil while unwrapping an Optional
value
when trying to load the data. I am not sure if the issue is in the storage or the retrieval. Has anyone been through this before?
From your code I see you are storing some array
// Your code
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
and retrieving a string
//Your code
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
There is probably a type mismatch, You store one type and retrieve another type.
While retrieving either use arrayForKey() or objectForKey() see the code below.
let tabledata = NSUserDefaults.standardUserDefaults().arrayForKey("\(identity.text!)listA")
or
let tabledata = NSUserDefaults.standardUserDefaults().objectForKey("\(identity.text!)listA")
If it is an array I would go with First one.
Here are the way that you can store and retrieved array of object with help of NSKeyArchive.
To Store array to NSUserDefault.
let placesData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(placesData, forKey: "places")
To Retrieved array from NSUserDefault.
let placesData = UserDefaults.standard.object(forKey: "places") as? NSData
if let placesData = placesData {
let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [Place]
print(placesArray)
}
Hope this help you.
Saving and Retrieving a String array to UserDefaults
Save array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.object(forKey: "SavedStringArray") as? [String] ?? [String]()
See more at How to save user settings using NSUserDefaults
What are you storing in the array?
If it's objects it won't work, if It's just strings or numbers then it should be fine.
Next steps you take should be to turn on exception breakpoints and maybe println() everything you can so you can pinpoint the exact whereabouts of the problem.
As a shot in the dark I would suggest maybe (identity.text!) is coming out as nil
Also you should probably change it to this
if let tabledata: NSArray = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA"){
myArray = [tabledata!]
tableView.reloadData()
}
This will make the code not even try to run unless there is a value it can use
Latest swift3 version to store array of data into userdefaults and get that array of data using keys
let nameArray = ["Ramu","JAGAN","Steve","Swift"]
let namesArrayData = NSKeyedArchiver.archivedData(withRootObject: nameArray)
UserDefaults.standard.set(namesArrayData, forKey: "arrayData")
RetriveData
let retriveArrayData= UserDefaults.standard.object(forKey: "arrayData") as? NSData
if let retriveArrayData= namesArrayData{
let retriveArray = NSKeyedUnarchiver.unarchiveObject(with: namesArraydata as Data) as? [nameArray]
print(retriveArray )
}
This has been changed in swift 3.
Note that this works with device but not playground or simulator
//store the array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.setValue(array, forKey: "history")
defaults.synchronize()
//Retrieve the array
if((UserDefaults.standard.array(forKey: "history")) != nil){
let historyWords = (UserDefaults.standard.array(forKey: "history") as? [String])!
print(historyWords)
}
Store into User Default:
let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]
//store in user default
UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")
Retrieving array from User Defaults:
if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{
print(arr)
}

Resources