0

I have the following Core Data model:

enter image description here

And I'm trying to update the many-to-many relationship between Speaker and TalkSlot from a JSON I receive from a REST API call.

I have tried dozens of ways, replacing my many-to-many by 2 one-to-many's, removing from one side or the other, but one way or the other I keep getting EXC_BAD_ACCESS or SIGABRT and I just don't understand the proper way to do it. Here is the last thing I tried:

for speaker in NSArray(array: slot!.speakers!.allObjects){
    if let speaker = speaker as? Speaker {
        speaker.mutableSetValueForKey("talks").removeObject(slot!)
    }
}
slot!.mutableSetValueForKey("speakers").removeAllObjects()

if let speakersArray = talkSlotDict["speakers"] as? NSArray {
    for speakerDict in speakersArray {
        if let speakerDict = speakerDict as? NSDictionary {
            if let linkDict = speakerDict["link"] as? NSDictionary {
                if let href = linkDict["href"] as? String {
                    if let url = NSURL(string: href) {
                        if let uuid = url.lastPathComponent {
                            if let speaker = self.getSpeakerWithUuid(uuid) {
                                speaker.mutableSetValueForKey("talks").addObject(slot!)
                                slot!.mutableSetValueForKey("speakers").addObject(speaker)
                            }
                        }
                    }
                }
            }
        }
    }
}

If it helps, the API I'm using is documented here as I'm trying to cache the schedule of a conference into Core Data in an Apple Watch extension. Note that I managed to store all the rest of the schedule without any issue. But for this relationship, each time I try to update it after storing it the first time, I get an EXC_BAD_ACCESS (or sometimes a SIGABRT), at a random place in my code of course. Any idea what I'm doing wrong?

Sebastien
  • 3,583
  • 4
  • 43
  • 82
  • Have you tried removing the app from the simulator and building again? That works for me when i update my Core Data model. – Gman9855 Oct 10 '15 at 22:44
  • Did you know that you can avoid nesting by using **commas** `,` ? – Mundi Oct 12 '15 at 19:48

1 Answers1

0

OK, after reading a few other questions associating Core Data EXC_BAD_ACCESS errors and multi-threading, I noticed that I was doing my caching on a NSURLSession callback. Once I called my caching function on the main thread using the code below, the EXC_BAD_ACCESS errors completely disappeared and now the data seems to be saved and updated properly:

dispatch_async(dispatch_get_main_queue(), { () -> Void in
   self.cacheSlotsForSchedule(schedule, data: data)
})
Sebastien
  • 3,583
  • 4
  • 43
  • 82