0

So I have an NSManagedObject called Student. There is a part of my code that sometimes breaks when I call a method on a Student object e.g student.performTask(). This gives me a EXC_BAD_ACESS which makes me believe it is a threading core data issue. However, one line before where the code breaks I access a variable from the object and there is no runtime error. So my question is: what is the difference between making a call to a variable in an NSManagedObject vs calling a method? What causes it to break for one but not for the other?

Note: the program breaks before executing a single line in the method.

Here is a snippet of my code:

let attendances = Attendance.createOrUpdateFromJsonDictionary(data!)
var seenIds = [NSNumber]()
for attendance in attendances {
    let student = attendance.student
    if !seenIds.contains(student.id) { //does not complain when accessing the id
       seenIds.append(student.id) 
       let oldCurrent = student.isCurrent //does not complain or break here
       student.setIsCurrent() //<- breaks here

Could the fact that attendance is also a NSManagedObject that has student as a relationship and I am grabbing student from attendance?

boidkan
  • 4,691
  • 5
  • 29
  • 43
  • are you running with the `-com.apple.CoreData.ConcurrencyDebug 1` flag? That will confirm or deny the threading issue. Second, update your question with the full error text as the rest of the error can be very helpful. What makes you think you are having a threading issue? Are you using multiple threads? Networking code perhaps? – Marcus S. Zarra Oct 06 '15 at 20:25
  • Yes this being called inside an Alamofire GET request which is threaded. I just added the flag but I am having trouble duplicating the bug now. I love debugging! There was no error text in the console, just the exc_bad_access at the line it was breaking. – boidkan Oct 06 '15 at 21:13

1 Answers1

0

If this is being called within another thread then you are violating the thread confinement rules of Core Data.

I highly suggest reading the concurrency section of the Core Data Programming Guide (recently updated) and apply the recommendations therein.

If you want to operate in the completion block of a third part networking library then you will need to call -performBlock: or -performBlockAndWait: against the context and only access the NSManagedObject instances within that block. Otherwise you will get unexpected and inconsistent results.

Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182