Save and read arrays into UserDefaults swift [duplicate] - ios

This question already has answers here:
Saving an image array with UserDefaults
(2 answers)
Closed 5 years ago.
I've always struggled with arrays; I´m trying to save some arrays into user defaults. my arrays are String, Double and UIImageView type. I declared them like:
var nameHospital = [String]()
var distanceBetweenLocations = [Double]()
var images = [UIImage]() // <-- Haven't tried with this yet
and I try to save them in UserDefaults like this...
UserDefaults.standard.set(nameHospital, forKey: "name")
And call theme like so
UserDefaults.standard.object(forKey: "name")
Then when I want to print them to see if it worked, it only prints one value (last value of the For Cycle) then I set my print inside the for and as I was expecting, it printed the value and then replaced it for the next value and so on.
What am I doing wrong? How can I call each value separately for further functions? And How can I do this but with my UIImage array? Thank you for your answers.

You are see this one : NSUserDefault
SAVE :
let kUserDefault = NSUserDefaults.standardUserDefaults()
kUserDefault.setObject(["KIRIT" , "MODI" , "FIRST" , "LAST"], forKey: "nameArray")
kUserDefault.synchronize()
READ :
kUserDefault.arrayForKey("nameArray")!
kUserDefault.objectForKey("nameArray")!
kUserDefault.valueForKey("nameArray")
For Swift 3
let kUserDefault = UserDefaults.standard
kUserDefault.set(["KIRIT" , "MODI" , "FIRST" , "LAST"], forKey: "nameArray")
kUserDefault.synchronize()
let data = kUserDefault.array(forKey: "nameArray")! as? [String] ?? [String]()
print(data)
for more info visit store value in userDefaults

Related

Ambiguous use of 'mutableCopy()' Swift3

I tried to update Swift 3 and I got the following error :
Ambiguous use of 'mutableCopy()'
Before update to swift 3. It runs well.
Swift 2.3
NSUserDefaults.standardUserDefaults().objectForKey("listsavednews")?.mutableCopy() as! NSMutableArray
Swift 3.0
(UserDefaults.standard.object(forKey: "listsavednews")? as AnyObject).mutableCopy() as! NSMutableArray
I found that mutableCopy in Swift3 return Any that doesnt have method mutableCopy() so that it needs to cast to AnyObject.
Any helps thanks.
I dont know why I can't comment.
Thanks all, I'll be using :
UserDefaults.standard.mutableArrayValue(forKey: "listsavednews")
mutableCopy is an Objective-C method from NSObject. There's little reason to use it in Swift 3.
Since you are dealing with UserDefaults and mutableCopy, you must be dealing with either an array or dictionary. Or it could be a string.
The proper way to do this in Swift 3 is to use the proper UserDefaults method to get an array or dictionary. And assign the result to a var. That combination will give you a mutable array or mutable dictionary.
var someArray = UserDefaults.standard.array(forKey: "somekey")
or:
var someDictionary = UserDefaults.standard.dictionary(forKey: "somekey")
In the two above cases, you end up with an optional since there might not be any data for the given key. And you also get a non-specific array or dictionary which isn't ideal. It would be better to cast the result to the appropriate type.
Let's say you have an array of strings and you want an empty array if there is nothing currently in user defaults. You can then do:
var someArray = UserDefaults.standard.array(forKey: "somekey" as? [String]) ?? []
Adjust as necessary if the array contains something other than String.
If you actually have a dictionary, the code would be similar.
var someDictionary = UserDefaults.standard.dictionary(forKey: "somekey") as? [String:String] ?? [:]
If your original object is just a string, then you could do:
var someString = UserDefaults.standard.string(forKey: "somekey") ?? ""

saving coins variable in swift 3 [duplicate]

This question already has an answer here:
Swift 3.0 save a score with SpriteKit
(1 answer)
Closed 6 years ago.
i am kinda new to swift and i need help with saving an int variable that holds the user's coins that they collect and saving it even after the app closes , so here is what i did , i have two scenes one represents startMenu which has the a struct that has the coins variable ( so i can easily control it from another scene ) , and the other scene which is GameScene , and in GameScene every time the user interacts with a coin node , it adds 1 to the coins variable in StarMenu Scene
here in my struct in StartMenu
struct Variables {
static var CoinsCollected = 0
}
and here is what i did to make it be saved
let defaults = UserDefaults.standard
defaults.set(Variables.CoinsCollected, forKey: "CoinsCollected")
defaults.synchronize()
and i have this line in GameScene inside my didbegin contact , when the user interacts with a coin
Variables.CoinsCollected += 1
and i have this line that updates the labelnode for the coins variable
coinsCollectedLabel = SKLabelNode(text: "coins: \(Variables.CoinsCollected)")
and everything works fine except that it doesn't get saved and i know i am missing something and i tried reading a lot of people's problem with the same issue but it didn't work, so if any of you guys could help me i would be highly appreciate it
You can do this in your Variables class so your coins are always saved in a persistent file:
class Variables {
static let userDefaults = UserDefaults.standard
struct Constants {
static let CoinsCollectedKey = "CoinsCollected"
}
static var CoinsCollected: Int {
get {
return userDefaults.integer(forKey: self.Constants.CoinsCollectedKey)
}
set(value) {
userDefaults.setValue(value, forKey: self.Constants.CoinsCollectedKey)
}
}
}
let defaults = UserDefaults.standard
...
//after Initializing Variables Instance
//get saved value
guard Variables.CoinsCollected = defaults.integer(forKey: "CoinsCollected") else {
print("Previously saved coins don't exist")
//create UserDefaults value for coins
defaults.set(Variables.CoinsCollected, forKey: "CoinsCollected")
}
I think it would be worth saving your entire Variables object instead, so that you can get any new values you add to your struct later - in which case you should serialize your Variables object using (for example)
//set object
defaults.set(Variables, forKey: "Variables")
//read object
let variables: Variables = defaults.object(forKey: "Variables")
//theoretically you should now be able to get CoinsCollected value within your retrieved object~
//e.g.
print(variables.CoinsCollected)

Retrieving bool array from NSUserdefaults in swift

I have defined an array like this in my iOS app
var array=[Bool]()
and assigning some bool values to this.After that I am storing this array in my user defaults in this way.
userDefaults.setObject(dm.array, forKey: "array")
Now I want to retrievw this array. So I did like this
dm.array=userDefaults.arrayForKey("array") as! Array
But here im getting an error
Down cast from '[AnyObject]?' to 'Array' only unwraps optional; did you mean to use '!'?
array = userDefaults.objectForKey("array") as? [Bool] ?? [Bool]()

How do I save a custom class in swift to NSUserDefaults? [duplicate]

This question already has answers here:
Using NSUserDefaults on arrays
(2 answers)
Closed 7 years ago.
I have made a custom class called test. I made a variable called "game" equal to test. I tried to save "game" to NSUserDefaults and attempted to print values from "game". After running the project I got an error: "Thread 1:signal SIGABRT". How do I save my custom object to NSUserDefaults without getting this error?
Here is my class:
class Test {
var boolean = false
var int = 1
var arr = ["one": 1]
}
Here is my saving code:
let defaults = NSUserDefaults.standardUserDefaults()
let game = Test()
game.arr = ["two": 3]
game.hi = true
game.int = 100
defaults.setObject(game, forKey: "SG")
let gameSet = defaults.objectForKey("SG")! as! Test
print(gameSet.int)
print(gameSet.boolean)
print(gameSet.arr["one"])
This is all in the viewDidLoad method. Excluding the test class.
From the documentation:
The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
You'll want to look at using NSKeyedArchiver instead for custom objects.

How do I save a swift array?

I am creating an app in Swift that manages tasks based off of priority. I currently place the tasks into an array. Does anybody know how I can save this array so that when I open the app I will still be able to access the data?
Use NSUserDefaults.
Save array:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(myArray, forKey: "myarray")
defaults.synchronize()
Read array:
myArray = defaults.dataForKey("myarray") as Array

Resources