Search code examples
iosswiftcore-datansmanagedobject

EXC_BAD_ACCESS KERN_INVALID_ADDRESS when accessing an NSManagedObject's Property


In my NSManagedObjects I have some properties that A) I do not want or need stored and B) are only computed once and only when they are needed so that the computations are not repeated (since they are somewhat expensive).

Here is the code I am talking about:

public class Sample: NSManagedObject {

    @NSManaged public var id: NSNumber
    @NSManaged public var anotherProperty: String?
    var orderedCustomObjects : Array<CustomObject>?

    func getOrderedCustomObjects() -> [CustomObject] {
        // application crashes on this line.
        if (orderedCustomObjects == nil) {
            // compute the custom object array here.
        }
        return orderedCustomObjects!
    }
}

public class CustomObject {
    var price : String?
    var quantity : String?
}

I am getting the following crash on a seemingly harmless line that checks if the property is nil before computing it:

Crashed: com.apple.main-thread EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000048

Any help would be appreciated on why I might be getting a crash from this.


Solution

  • As mentioned in the comments the answer was that the object was being deleted on a different thread which caused it to be deallocated on the main thread.