await withTaskGroup with Core Data sometimes fails - swift

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.

Related

Updating Coredata using threads

I am trying to update an entity in Coredata using the background/thread. I am passing two variables in the below function, one is date and the other one is Account that has 'to one' relationship with the transaction attribute. I am getting an error when I execute the below code.
The goal is to perform updates to coredata without freezing the tableview and other controls/views.
ERROR - *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'account' between objects in different contexts
public class Transaction: NSManagedObject {
#NSManaged public var transDate: Date?
#NSManaged public var account: Account?
class func addTransaction(transDate : Date, transAccount : Account){
let appDelegate = NSApplication.shared.delegate as! AppDelegate
appDelegate.persistentContainer.performBackgroundTask({ (context) in
let entity = NSEntityDescription.entity(forEntityName: "Transaction", in: context)
let CD = Transaction(entity: entity!, insertInto: context)
CD.transDate = transDate //updated successfully
CD.account = transAccount//Gets an error while performing this line of code.
do {
try context.save()
}
catch {
print("error in saving Transaction data")
}
})
}
}
You can not use objects from different context together, the transaction object is created in your background context but the account object is from your main context.
The solution is to get the corresponding account object from the background context using the objectID which is always the same between contexts.
let account = context.existingObject(with: transAccount.objectID)) as? Account
CD.account = account
Note that account is optional here so you need to add some error handling in case it is nil, this should never happen but still it needs to be handled.

Swift 5 Firestore: Checking if collection exists in database

I'm trying to check if a certain collection exists in my Firestore database, and here is my code for doing so:
let db = Firestore.firestore()
db.collection(pickedClass).getDocuments { (snapshot, error) in
if error == nil && snapshot != nil {
if snapshot!.documents.count > 0 {
for document in snapshot!.documents {
let documentData = document.data()
let info = documentData["info"] as! [String: Any]
output.append(object)
}
self.performSegue(withIdentifier: "showTutors", sender: output)
} else {
self.createAlert(title: "No Tutors Found", message: "Sorry, there are no tutors for this class", buttonMsg: "Okay")
}
}
}
The exception I get from running this apparently comes from the second line db.collection(pickedClass).getDocuments, and is as follows:
*** Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Invalid collection reference. Collection references must have an odd number of segments, but has 0'
terminating with uncaught exception of type NSException
The bizarre thing is that most times this isn't an issue and the user sees the alert when the collection doesn't exist, but sometimes this happens. I never faced this issue until today, and I've been running this database and this snippet of code for over 2 months now.
Would really appreciate any help!
Hi, I'm implementing FireStore in first time as I study I found this
answer you can use this below mentioned code.
Firestore.firestore().collection("YOUR_COLLECTION_NAME_HERE")
.document("INSIDE_YOUR_COLLECTION_USE_DOCUMENT_ID_HERE_WHICH_YOU_WANT_TO_CHECK")
.getDocument { (document, error) in
debugPrint(document?.exists)
if document?.exists ?? false {
// EXIST
} else {
// NOT-EXIST
}
}

saving data array causes crash swift

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

Ignore records in FirebaseDB with swift

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})

Swift: How to avoid deadlock occuring inside for loop of asynchronous functions?

I have a for loop - running 6 times - containing an async function that uploads an object to a database. When called the function only uploads 3 - 4 objects and for the remaining 2 - 3 the console prints:
fServer reported an error: FAULT = 'Server.Processing'
[java.lang.RuntimeException: java.lang.RuntimeException:
java.lang.RuntimeException:
com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException:
Deadlock found when trying to get lock; try restarting transaction]
I've read other threads regarding this issue and I followed the advise to use dispatch groups. Unfortunately it's still not working for me and I do not understand why. How can I avoid these deadlocks from happening?
func uploadObjects() {
let myGroup = dispatch_group_create()
self.backendless.initApp(self.APP_ID, secret: self.SECRET_KEY, version: self.VERSION_NUM)
for object in objects {
dispatch_group_enter(myGroup)
let dataStore = backendless.data.of(Game.ofClass())
// save object asynchronously
dataStore.save(
game,
response: { (result: AnyObject!) -> Void in
dispatch_group_leave(myGroup)
let obj = result as! Game
print("Game saved: \(obj.objectId)")
},
error: { (fault: Fault!) -> Void in
print("fServer reported an error: \(fault)")
})
}
dispatch_group_notify(myGroup, dispatch_get_main_queue(), {
print("Finished all requests.")
})
}