1

Extra info:

I have a messaging view in which I have a UITextView of which I save the text in the conversation's variable draft in the viewWillDisappear.

When the app tries to refresh the user's access code, they might get a "could not refresh" response, and the app logs the user out (only one device may be logged in at one time in this app).

In the logout method, I remove all app settings and empty out Core Data, then I set a new rootViewController and perform makeKeyAndVisible.

Question:

Now that you know all this, setting the rootViewController calls viewWillDisappear, which in turn tries to set the draft variable on a conversation that no longer exists in Core Data...

What can I do to solve this?

vrwim
  • 13,020
  • 13
  • 63
  • 118

1 Answers1

2

The simplest and fastest fix would be, when setting the draft:

if let context = conversation.managedObjectContext {
   // you have a valid conversation, you can assign the draft
}

If the managedObjectContext is nil, this means the object has been deleted from Core Data.

EDIT

This answer provides a better way to detect if a managed object has been deleted from Core Data.

I would advise you to rethink the whole logout (clearing of resources) approach since yours is not going to scale in the future.

Community
  • 1
  • 1
Teo
  • 3,394
  • 11
  • 43
  • 73
  • But I don't know where it will happen next, do I need to check every single time if `managedObjectContext` is `nil` when I want to write to a coredata object? The refresh can fail at any time. – vrwim May 19 '15 at 12:29
  • Why don't you just rethink your whole approach? When you log out, why don't you get rid of all the resources, including the managed objects you already fetched? If the logout method is called from the same controller that interacts with these objects you could directly get rid of the resources. Otherwise you could use notifications in order to let everybody know that a logout has been or will be performed. – Teo May 19 '15 at 12:39