Search code examples
swiftxcodecore-datafetchrequest

Why is the app crashing when doing a Fetch Request in Core Data


Core Data is crashing when doing a fetch request but I can't understand why. The error is suggesting EXC_BAD_ACCESS but it doesn't always occur for this particular fetch request. Basically when I zoom in and out on the mapView (MKMapKit), it's at that point it crashes.

For my mapView I use the following code:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let userStatus = CoreDataUserLocationManagement().returnUsersLastKnownStatus()
    if (annotation is MKUserLocation) && userStatus != 3 {

As you can see from the above, this is when I request the lastKnownStatus, but as mentioned it doesn't always crash.

This fetch crashes here

func returnUsersLastKnownStatus() -> Int16 {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "UsersLocationDetails")
    do {
        if let fetchResults = try managedObjectContext.fetch(fetchRequest) as? [UsersLocationDetails] {
            if fetchResults.count != 0 {
                let managedObject = fetchResults[0]
                return managedObject.lastKnownStatus
            }
        }
    }
    catch {
        print("Catch error retrieving last known status to Core Data")
    }
    return 3
}

The log is:

    Printing description of fetchRequest:
(NSFetchRequest) fetchRequest = 0x0000000283a5be20 {
  baseNSPersistentStoreRequest@0 = {
    baseNSObject@0 = {
      isa = NSFetchRequest
    }
    _affectedStores = 0x0000000000000000
  }
  _groupByProperties = 0x0000000000000000
  _havingPredicate = 0x0000000000000000
  _additionalPrivateIvars = 0x0000000281044100
  _valuesToFetch = 0x0000000000000000
  _entity = 0x0000000282684dc0 {
    baseNSObject@0 = {
      isa = NSEntityDescription
    }
    _cd_rc = 12
    _snapshotClass = 0x000000028208a760
    _versionHashModifier = 0x0000000000000000
    _versionHash = some {
      some = 0x0000000102faea90 {
        baseNSData@0 = {
          baseNSObject@0 = {
            isa = _PFEncodedData
          }
        }
        _aData = some {
          some = 0x00000002811c7e60 {
            baseNSData@0 = {
              baseNSObject@0 = {
                isa = _PFVMData
              }
            }
            _cd_rc = 1732
            _length = 40944
            _payload = 0x0000000102fac000
          }
        }
        _byteCount = 32
        _reserved = 0
      }
    }
    _model = some {
      some = 0x00000002832a9400 {
        baseNSObject@0 = {
          isa = NSManagedObjectModel
        }
        _dataForOptimization = some {
          some = 0x00000002811c7e60 {...}
        }
        _optimizationHints = 0x0000000102fb5850
        _additionalPrivateIvars = 0x00000002811c0120
        _entities = some {
          some = 0x000000028239f9f0 {
            baseNSKnownKeysDictionary1@0 = {
              baseNSKnownKeysDictionary@0 = {
                baseNSMutableDictionary@0 = {
                  NSDictionary = {
                    NSObject = {
                      isa = NSKnownKeysDictionary2
                    }
                  }
                }
              }
              _cd_rc = 0
              _count = 14
              _keySearch = some {
                some = 0x0000000102faeb10 {
                  baseNSKnownKeysMappingStrategy1@0 = {
                    baseNSKnownKeysMappingStrategy@0 = {
                      baseNSObject@0 = {
                        isa = NSKnownKeysMappingStrategy2
                      }
                    }
                    _cd_rc = -2128839072
                    _reserved64 = 2
                    _table = 0x0000000102faeb40
                    _length = 14
                    _reserved1 = 0x0000000000000000
                    _keys = 0x0000000102faec28
                  }
                }
              }
              _values = {}
            }
          }
        }
        _configurations = 0x00000002811c0100 1 key/value pair
        _fetchRequestTemplates = 0x0000000000000000
        _versionIdentifiers = 0x00000002811c0140 1 element
      }
    }
    _classNameForEntity = some {
      some = 0x0000000102fad388 {
        base_PFAbstractString@0 = {
          baseNSString@0 = {
            baseNSObject@0 = {
              isa = _PFEncodedString
            }
          }
        }
        _cd_rc = 0
        _length = 20
        _sourceData = some {
          some = 0x00000002811c7e60 {...}
        }
      }
    }
    _instanceClass = 0x00000002835b9b70
    _name = some {
      some = 0x0000000102fad388 {...}
    }
    _rootentity = 0x0000000282684dc0 {...}
    _superentity = 0x0000000000000000
    _subentities = 0x0000000000000000
    _properties = some {
      some = 0x00000002835b8720 {
        baseNSKnownKeysDictionary1@0 = {
          baseNSKnownKeysDictionary@0 = {
            baseNSMutableDictionary@0 = {
              NSDictionary = {
                NSObject = {
                  isa = NSKnownKeysDictionary2
                }
              }
            }
          }
          _cd_rc = 0
          _count = 9
          _keySearch = some {
            some = 0x0000000102fb0bf0 {
              baseNSKnownKeysMappingStrategy1@0 = {
                baseNSKnownKeysMappingStrategy@0 = {
                  baseNSObject@0 = {
                    isa = NSKnownKeysMappingStrategy2
                  }
                }
                _cd_rc = -2128839072
                _reserved64 = 2
                _table = 0x0000000102fb0c20
                _length = 9
                _reserved1 = 0x0000000000000000
                _keys = 0x0000000102fb0cd0
              }
            }
          }
          _values = {}
        }
      }
    }
    _propertyMapping = some {
      some = 0x0000000102fb0bf0 {...}
    }
    _userInfo = 0x0000000000000000
    _flattenedSubentities = 0x0000000281ff60d0 1 element
    _kvcPropertyAccessors = 0x00000002832a92c0
    _modelsReferenceIDForEntity = 13
  }
  _predicate = 0x0000000000000000
  _sortDescriptors = 0x0000000000000000
  _batchSize = 0
  _fetchLimit = 0
  _allocationSize = 0
  _relationshipKeyPathsForPrefetching = 0x0000000000000000
}

Also just noticed this in Xcode:

(NSPersistentStoreRequest) CoreData.NSPersistentStoreRequest = <parent failed to evaluate: invalid load address>

Solution

  • So it turns out that it was this piece of code that code that was causing the issue. I have no idea why as the crash wasn't reporting this but as soon as I commented it out, it no longer crashes.

    @IBAction func centerUserBtnTapped(_ sender: Any) {
        let location = CLLocationCoordinate2D(latitude: locationManager.location?.coordinate.latitude ?? 0.0, longitude: locationManager.location?.coordinate.longitude ?? 0.0)
        let span = MKCoordinateSpan.init(latitudeDelta: self.mapView.region.span.latitudeDelta, longitudeDelta: self.mapView.region.span.longitudeDelta)
        let region = MKCoordinateRegion(center: location, span: span)
        self.mapView.setRegion(region, animated: true)
        self.mapView.setUserTrackingMode(.follow, animated: true)
    }
    

    Instead I simplified it to the normal approach:

    @IBAction func centerUserBtnTapped(_ sender: Any) {
        mapView.setUserTrackingMode(.follow, animated: true)
    }