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

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.

Related

Swift Can't append to String array [duplicate]

This question already has answers here:
Simple swift array append not working
(3 answers)
Closed 4 years ago.
I have this array defined inside a class:
var pickOption: [String]?
inside my classes init, I am trying to append to the array:
override init!(reuseIdentifier identifier: String!) {
self.pickOption?.append("aaa")
print(self.pickOption)
}
but self.pickOption is returning nil, why? and how can I fix it?
With first statement var pickOption: [String]? you have just declared the array of type string but never allocate the memory. As this is optional type, it will be nil at the time of declaration.
You need to allocate memory for array before using it. You can declare array as this var pickOption = [String]() and rest of code will do the work!!
You have to init it declare it like this
var pickOption = [String]()
as this line
self.pickOption?
with the optional won't run as in it's moment pickOption is nil

Save and read arrays into UserDefaults swift [duplicate]

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

ios - filter two arrays with objects Swift [duplicate]

This question already has answers here:
How to remove common items from two struct arrays in Swift
(3 answers)
Closed 6 years ago.
I have got two arrays with objects.
var filteredData:[MainData] = [MainData]()
var removeData:[MainData] = [MainData]()
struct MainData {
var open:NSTimeInterval
var works = [Visit]()
}
I want remove data from filteredData using function filter with parameter filteredData.open == removeData.open
I can't filter two arrays with objects.
You can try like this, first get an Array of open from removeData array and check that it is contains object from the filteredData Array opens.
let opens = removeData.map { $0.open }
filteredData = filteredData.filter { !opens.contains($0.open) }

Crash set variable extension Swift [duplicate]

This question already has answers here:
Property getters and setters
(12 answers)
Closed 8 years ago.
I got a crash when i try to set a variable inside a extension:
extension String {
var index: Int {
get {
return self.index
}
set {
self.index = newValue
}
}
}
var o: String = "tre"
o.index = 87 // crash here
println(o.index) // Even here
i tried everything, without any success.
Thanks in advance for your help.
You cannot add new stored variables to a type using extensions.
You are making a loop by infinitely setting or getting a property.
You cannot add new stored properties with extension, only computed ones that are not backed by a property.

Set objects to empty NSDictionary in Swift [duplicate]

This question already has answers here:
Swift dictionary bug?
(6 answers)
Closed 8 years ago.
I can create an NSDictionary
var namesDictionary=Dictionary<String,String>()
namesDictionary["Jacob"] = "Marry"
But, when I create a empty dictionary like coded below, line 1 i okie, but line 2 (adding values) throws an error.
var namesDictionary =[:]
namesDictionary["Jacob"] = "Marry"
Error is "Cannot assign to the result of this expression". Is there any other way to assign the values.
It looks like it's an issue with swift interpreting the type of your dictionary. Try explicitly typing your empty dictionary.
var namesDictionary: Dictionary<String, String> = [:]
namesDictionary["Jacob"] = "Marry"
I think a better use for [:] is for emptying an already defined dictionary. If you add a third line namesDictionary = [:], you will be able to call namesDictionary["Jacob"] = "Marry" again since the compiler knows what type of dictionary it is from the inital declaration.

Resources