I am trying to save an array of Tuple in UserDefaults. To do this I found on the internet that NSKeyedArchiver.archivedData can be use to convert the Tuple data into the NSData type. After conversion the tuple data can easily be saved in UserDefaults.
Below is the Tuple array which I want to save
[((Color:Color, ID:ID),(DefectType:Type,DefectCode:Code))]
but It gives me the below error
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[_SwiftValue
encodeWithCoder:]: unrecognized selector sent to instance 0x1702d47b0
Below is the code I am using
let DATA = ((Color:Color, ID:ID),(DefectType:Type,DefectCode:Code))
let ArchivedDATA = NSKeyedArchiver.archivedData(withRootObject: [DATA])
print("ArchivedDATA =",ArchivedDATA)
defaults.setValue(ArchivedDATA, forKeyPath: "\(self.CodeLabel.text!)")
if let data = defaults.object(forKey: "\(self.AuditCodeLabel.text!)") as? NSData{
SavedDefects = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? [((Color:UIColor, ID:String),(DefectType:String,DefectCode:String))]
print("dataUnarchived =",SavedDefects)
}
Please anyone help me to save tuple array into the UserDefaults.If I am going wrong, kindly tell me the proper way to save this.
Thank you
Related
What I want to do:
I want to get an array from UserDefaults that I saved beforehand and append a custom object to it. Afterwards I want to encode it as a Data-type again and set this as the UserDefaults Key again.
My problem:
The encoding part is what is not working as intended for me.
It says: -[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x60000011a540
But I do not know how to fix this.
Below is my code for more context:
do {
let decoded = defaults.object(forKey: "ExArray") as! Data
var exo = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(decoded) as! [Exerc]
exo.append(datas[indexPath.row])
let enco = try NSKeyedArchiver.archivedData(withRootObject: exo, requiringSecureCoding: false) <- Here is the error
defaults.set(enco, forKey: "ExArray")
} catch {
print("Error encoding custom object NOSEARCHO")
}
This is how Exerc looks:
struct Exerc: Codable {
var title: String
var exID: String
}
Seems like you are not using the archiver features, so why don't you just use the codable?
do {
let key = "ExArray"
let decoded = defaults.data(forKey: key)!
var exo = try JSONDecoder().decode([Exerc].self, from: decoded)
exo.append(datas[indexPath.row])
let enco = try JSONEncoder().encode(exo)
defaults.set(enco, forKey: key)
} catch {
print("Error encoding/decoding custom object NOSEARCHO", error)
}
It just a simple refactored MVP of the original code, but you can even work a bit on this and make it human readable right in the plist file!
I tried adding an item to an arrar and saving in Userdefault but the app crashed and I would love anyone to point me to what I am doing wrong
private func putArray(_ value: GMSAutocompletePrediction?, forKey key: String) {
guard let value = value else {
return
}
log("THE MESSAGE \(value)", .fuck)
var newArray = getArray(forKey: key)
log("THE MESSAGE ARRAY \(newArray)", .fuck)
if newArray.contains(value) {
newArray.remove(at: newArray.firstIndex(of: value)!)
} else {
newArray.append(value)
}
storage.setValue(NSKeyedArchiver.archivedData(withRootObject: newArray), forKey: key)
}
error from crash
[GMSAutocompletePrediction encodeWithCoder:]: unrecognized selector sent to instance 0x2818f9ce0
2019-09-26 13:40:07.300856+0100 MAX.NG Staging Debug[4440:1410011] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GMSAutocompletePrediction encodeWithCoder:]: unrecognized selector sent to instance 0x2818f9ce0'
GMSAutocompletePrediction doesn't conform to NSCoding so you can't save it to user defaults , you may extract important details from it and make a custom model to save
This question already has answers here:
Attempt to insert non-property list object when trying to save a custom object in Swift 3
(6 answers)
Closed 3 years ago.
Here is the full error message I am getting:
as an NSUserDefaults/CFPreferences value for key Login_Data
2019-04-02 09:44:56.191207+0530 Level Up[238:4101] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object
Here is my Code :
let data = response.result.value as! NSDictionary
print(data)
if data["error-code"] != nil {
if data.object(forKey: "error-code")as! String == "\(200)"
{
let arrTimer = ((data.object(forKey: "data") as! NSDictionary).object(forKey: "timers") as! NSArray).mutableCopy() as! NSMutableArray
UserDefaults.standard.set(arrTimer , forKey: "ArrayTimer")
UserDefaults.standard.set((data.object(forKey: "data") as! NSDictionary), forKey: "Login_Data")
I am getting this when am changing user e-mail from backend. For the fresh user it works fine.
I hope this is enough code to give you an idea o what I am trying to do.
Looks like the issue is that the dictionary has NSNull or nil values and trying to store that in UserDefaults doesn't work. The library should probably use NSKeyedArchiver to get around that. Convert dictionary to data then save it in UserDefaults.
I am using core data. For fetching data I want to give predicate as string. I have stored predicate in string attribute in database.
Below is code I am trying
let request = NSFetchRequest<Tasks>(entityName: "Tasks")
print("Query is .." ,item.query!)
request.predicate = NSPredicate(format: item.myqueryString!)
myqueryString is string attribute in core data where I am storing predicate as -
projectName == "spot"
But on fetching data it is giving error "NSInvalidArgumentException', reason: 'keypath spot not found in entity".
Anyone can explain what is wrong? Thanks in advance
Im working on a swift app that displays records from firebase to a table view controller.
I have successfully been pulling in all data, But I have since added another field to the DB called "secretKey".. This doesn't not need to be used on the table view as its used elsewhere in the app
But now each time I try to run the app I get the following errors
2018-05-07 12:24:24.616490+0100 Loop Guardian[21847:9857567] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSTaggedPointerString 0xa030818c015ea1f9> valueForUndefinedKey:]: this class is not key value coding-compliant for the key createdAt.'
*** First throw call stack:
(0x18204b164 0x181294528 0x18204ae2c 0x1829fe434 0x182944e20 0x182944874 0x18297d930 0x1030084b0 0x103008740 0x1030f2840 0x1044892cc 0x10448928c 0x10448dea0 0x181ff3344 0x181ff0f20 0x181f10c58 0x183dbcf84 0x18b6695c4 0x10301de44 0x181a3056c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
This only happens when the secretKey is present in the DB.. If I remove it the app works fine.
I somehow need to ignore this field
Heres the code used to pull the records from the DB
func observeMessages() {
let key = UserDefaults.standard.value(forKey: "uid") as! String
DBrefs.databaseMessages.child(key).observe(.value, with: { (snapshot) in
if snapshot.exists() {
let messageData = snapshot.value as! Dictionary<String, AnyObject>
self.dataArr = []
for (key,data) in messageData {
self.dataArr.append(data)
}
//THIS IS WHERE THE ERROR IS THROWN.. THREAD 1: SIGNAL SIGABRT
self.dataArr = (self.dataArr as NSArray).sortedArray(using: [NSSortDescriptor(key: "createdAt", ascending: true)]) as [AnyObject]
self.tblMessage.reloadData()
}
else {
}
})
}
Any help is appreciated
Thanks
Oliver
for (key,data) in messageData {
if (key == "secreyKey") {
continue;
}
self.dataArr.append(data)
}
Also use Swift method to sort the Array. Don't use NSArray use Array instead.
Like below code:
self.dataArr.sorted(by: {$0["createdAt"] as? Int64 ?? 0 < $1["createdAt"] as? Int64 ?? 0})