ioscrashstate-restorationnsuseractivity

How to force NSUserActivity to save?


NSUserActivity has a method setNeedsSave:.

[userActivity setNeedsSave:YES];

Unfortunately it doesn't save at once, but just tells a user activity object that it should be saved in the future. In case of a crash the state may not be saved. As a result the state may not be restored after a crash.

Does any workaround exist? Is it possible to implement the method save for NSUserActivity myself in a category to force it to save each time when the state updates, not only when the system decides to do saving?


Solution

  • The [userActivity setNeedsSave:YES]; is only necessary in specific cases. You do not need it to ensure your activity gets saved.

    Instead, make sure the view controller you inject the activity is visible because if it is not, it will not save it; therefore, it will not get suggested in the spotlight.

    If the view controller is visible by injecting the activity, the system should do everything for you. Otherwise, you might need to execute the becomeCurrent to force it to save.