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
Related
I have the following taskGroup, using the async/await concurrency in Swift 5.5, where I iterate over meters, fetching onboardingMeter from Core Data. This works ok in around 4 out of 5 times, but then crashes the iOS app. I am testing this with deleting the app from the iOS device, and run the onboarding from the start. Sometimes I can run this with no problems 4 or 5 or 6 times in a row, then it suddenly crashes with the following error:
2021-09-05 09:11:01.095537+0200 Curro[12328:1169419] [error] error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
2021-09-05 09:11:01.095954+0200 Curro[12328:1169419] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet addObject:]: attempt to insert nil'
*** First throw call stack:
(0x1857b105c 0x19dc63f64 0x1858ba538 0x1858c5df8 0x1857c68bc 0x18ce313d8 0x18cd13314 0x18cd140cc 0x105616700 0x105626a90 0x185769ce4 0x185723ebc 0x1857373c8 0x1a0edd38c 0x1880dae9c 0x187e58864 0x18d36da2c 0x18d29ab70 0x18d27bf2c 0x1048bba04 0x1048bbab0 0x10551da24)
libc++abi: terminating with uncaught exception of type NSException
This is the code where it fails, the let onboardingMeter = await OnboardingMeter.fromMeterDict is never returned, I don't see the second print statement when it fails.
Is this an error in the Swift beta, or have I made any mistake here? I will try again when a new iOS 15 beta arrives, and when the official release of iOS 15 comes out.
await withTaskGroup(of: OnboardingMeter.self) { group in
for (number, codableAddress) in meters {
group.addTask {
print("The following statement sometimes fails to return an onboarding meter, resulting in a crash")
let onboardingMeter = await OnboardingMeter.fromMeterDict(number, address: codableAddress, in: moc)
print("onboardingMeter:", onboardingMeter)
return onboardingMeter
}
}
for await meter in group {
onboardingMeters.append(meter)
}
}
The OnboardingMeter.fromMeterDict function:
extension OnboardingMeter {
static func fromMeterDict(_ number: String, address: CodableAddress, in moc: NSManagedObjectContext) async -> OnboardingMeter {
let me: OnboardingMeter = await moc.findOrCreateInstance(of: self, predicate: NSPredicate(format: "number == \(number)"))
let address = await Address.createOrUpdate(from: address, in: moc)
await moc.perform {
me.address = address
me.number = number
}
return me
}
}
and findOrCreateInstance:
func findOrCreateInstance<T: NSManagedObject>(of type: T.Type, predicate: NSPredicate?) async -> T {
if let found = await self.findFirstInstance(of: type, predicate: predicate) {
return found
} else {
return T(context: self)
}
}
Although I'd need to see more code to confirm this, I believe that you're returning a managed object that is already registered to a managed object context. It is only valid to refer to such registered objects within the closure of a perform call. If you need to refer to a managed object between different execution contexts, either make use of the object ID and refetch as needed, or make use of the dictionary representation option of the fetch request:
let request: NSFetchRequest = ...
request.resultType = NSManagedObjectIDResultType // or NSDictionaryResultType
return request.execute()
I'd strongly encourage you to watch this video from WWDC. At the minute 10:39 they're talking exactly about this.
I'm developing an app, and I need save data, so im using Core Data, and unfortunately in not a Core Data expert
When I run the app for the first time, it works and saves the data (I checked the *.sqlit file), but if re-run the app give me this erros
2020-09-12 02:52:02.539123+0100 photoUniq_ios_v3[6106:338281] -[photoUniq_ios_v3.PUWorkspace initWithCoder:]: unrecognized selector sent to instance 0x600000a562e0
2020-09-12 02:52:02.539730+0100 photoUniq_ios_v3[6106:338281] [error] fault: exception raised during multi-threaded fetch -[photoUniq_ios_v3.PUWorkspace initWithCoder:]: unrecognized selector sent to instance 0x600000a562e0 ((null))
CoreData: fault: exception raised during multi-threaded fetch -[photoUniq_ios_v3.PUWorkspace initWithCoder:]: unrecognized selector sent to instance 0x600000a562e0 ((null))
2020-09-12 02:52:02.539958+0100 photoUniq_ios_v3[6106:338281] [error] CoreData: exception raised during multi-threaded fetch -[photoUniq_ios_v3.PUWorkspace initWithCoder:]: unrecognized selector sent to instance 0x600000a562e0 ((null))
2020-09-12 02:52:02.540290+0100 photoUniq_ios_v3[6106:338281] [error] error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x60000174c2a0> , -[photoUniq_ios_v3.PUWorkspace initWithCoder:]: unrecognized selector sent to instance 0x600000a562e0 with userInfo of (null)
CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x60000174c2a0> , -[photoUniq_ios_v3.PUWorkspace initWithCoder:]: unrecognized selector sent to instance 0x600000a562e0 with userInfo of (null)
2020-09-12 02:52:02.589331+0100 photoUniq_ios_v3[6106:338281] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[photoUniq_ios_v3.PUWorkspace initWithCoder:]: unrecognized selector sent to instance 0x600000a562e0'
...
libc++abi.dylib: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[photoUniq_ios_v3.PUWorkspace initWithCoder:]: unrecognized selector sent to instance 0x60000344d3e0'
terminating with uncaught exception of type NSException
I have an environment object
SceneDelegate.swift
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView
.environmentObject(PU(ctx: context))
.environmentObject(PartialSheetManager())
)
PU.swift
class PU: NSManagedObject{
let id = UUID()
var defaultWorkspace:PUWorkspace{
self.cd_xWorkspaces!.first!
}
init(ctx:NSManagedObjectContext?) {
super.init(entity: PUPhotouniq.entity(), insertInto: ctx)
self.cd_xGallary = PUGallary(ctx: self.managedObjectContext)
self.cd_xWorkspaces = Array()
self.cd_xWorkspaces!.add(PUWorkspace(ctx: self.managedObjectContext))
}
}
PUWorkpace.swift
import Foundation
import SwiftUI
import CoreData
class PUWorkspace:NSManagedObject {
let id = UUID()
#NSManaged var cd_nome:String?
#NSManaged var cd_porcessedxFoldres:[PUFolder]?
#NSManaged var cd_xFoldres:[PUFolder]?
#NSManaged var cd_originalxFoldres:[PUFolder]?
#Published var cd_cover:UIImage = UIImage() //Init
var defaultFolder:PUFolder{
cd_xFoldres!.first ?? PUFolder(ctx: self.managedObjectContext)
}
init(ctx:NSManagedObjectContext?) {
super.init(entity: Self.entity(), insertInto: ctx)
self.cd_cover = UIImage.defaultImage
self.cd_nome = String.defaultName
self.cd_xFoldres = []
self.cd_xFoldres!.add(PUFolder(ctx: self.managedObjectContext))
self.cd_originalxFoldres = []
self.cd_porcessedxFoldres = []
}
}
and a few functions
to fetch the data
#FetchRequest(entity: PU.entity(), sortDescriptors: []) var photoUniq2:FetchedResults<PU >
what can cause the error and how I can solve it?
I'm using Swift 5.
Why does an NSInvalidArgumentException occur when responseValues["CustomerID"] == '<null>'?
Obviously the if responseValues["CustomerID"] is NSNull is not doing the trick. What check should be in place to avoid the NSInvalidArgumentException
self.api.getCustomerId(callback: { getIDResult in
if let responseValues = getIDResult["ResponseValues"] {
print("GET CUSTOMER ID RESULT")
print(responseValues)
if responseValues["CustomerID"] is NSNull { // <---- crashes here when null
print("CustomerID is null")
}
else{
print("CustomerID is NOT null")
}
}
})
Succesful result
GET CUSTOMER ID RESULT
{
CustomerID = 403254;
}
CustomerID is NOT null
Crashing result when encountering a null customer id
GET CUSTOMER ID RESULT
{
CustomerID = "<null>";
}
crashes with the following
019-11-21 12:13:16.819033-0500 MyApp[29412:4207932] -[NSNull _fastCStringContents:]: unrecognized selector sent to instance 0x7fff80615710
2019-11-21 12:13:16.820557-0500 MyApp[29412:4207932] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull _fastCStringContents:]: unrecognized selector sent to instance 0x7fff80615710'
Someone was questioning whether the value was actually null, here's some debug info on that dictionary:
if responseValues is a dictionary, you can do this
if let customerId = responseValues["CustomerID"] as? String
{
print(customerId)
}
else
{
print("customer id isn't available")
}
if you want to know if is null, you have to change to Codable
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})
I like to add "abc" to eventTextField.text and save it to the attributeeventName below
eventInformation.setValue(eventTextField.text, forKey: "eventName")
I tried this
let abcString = "abc"
eventInformation.setValue(eventTextField.text?.append(abcString), forKey: "eventName")
but my app is crashing with following error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for
attribute: property = "eventName"; desired type = NSString; given type
= _SwiftValue; value = ().'
The error occurs because append is mutating but does not return anything,
that's the _SwiftValue; value = () (Void)
You need an extra step:
let abcString = "abc"
eventTextField.text?.append(abcString)
eventInformation.setValue(eventTextField.text, forKey: "eventName")