ELKA ELKA - 1 year ago 100
Swift Question

Fetch relationship of deleted entity. (Crash)

On app startup, I am deleting old CoreData rows in a background thread and below is the code that I have. My problem is similar to City-Streets problem. So, I have two entities, Street and City and I have a relationship City <->> Street as a city has many streets.

I got a rare crash on Crashlytics just where it's stated in the code below. The crash never happened to me and I was unable to replicate it. I am not sure if the problem could be that we shouldn't fetch the relationships of a deleted entity. Can someone give me some explanations or the steps to reproduce the issue? (I want to make sure that this is the cause)

//fetch the entities I want to delete
let streets = fetchEntitiesToDeleteInContext(context)

for street in streets{

let city: City = street.city // NO crash here
let cityName: String = city.name //crash here but I am sure that name is not nil

Answer Source

You can just get the city object before you delete a street.

Also, your code does not make any sense. You are defining variables in the scope of the for loop and not using them. - But you explained that this is just an excerpt.

Note that the behavior is undefined so it is not guaranteed to crash. No need to worry about why it worked before.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download