Search code examples
iosswiftcore-datansfetchrequest

How to avoid Fetching Core data Entity as Fault?


During my screen transitions I have a Core data model class object which passes from one to other class. But during this sometimes its "nil" and when I try to log it I find it has returned a fault. While fetching it I have set :

        fetchRequestObject.returnsObjectsAsFaults = false

I am new to core data. Below is the log when I tried to print the Object :

    Optional<"MyEntity">
      - some : <ProjectName.MyEntity: 0x2822acdc0> (entity: "MyEntity"; id: 0x9ddeded1ada58e31 <x-coredata://27FC66FC-4FDF-4B40-9541-F4E90622906C/MyEntity/p34705> ; data: <fault>)

Many times it prints and works fine with its attributes and values. But other times it is "nil".


Solution

  • I have faced similar issue

    Faults are in general not something to worry about (CoreData will automatically fire the fault and populate the object as soon as you access any of its attributes).

    But in this instance I suspect something more nefarious is happening: the CoreData is instantiated locally in that fetch method, and I fear it is being deallocated (together with the associated managedObjectContext) as soon as the method completes. Your return array consequently contains NSManagedObjects from a context which has been deallocated. To check, try making managedObjectContext a property (a global var) rather than a local variable. That should be enough to keep a permanent reference to the context (which in turn will have strong references to the underlying stack) and prevent it being deallocated.