According to NSObject’s documentation:
Important: Note that when an
application terminates, objects may
not be sent a dealloc message since
the process’s memory is automatically
cleared on exit — it is more
efficient simply to allow the
operating system to clean up resources
than to invoke all the memory
management methods.
That’s fine, but if my objects needs to do something on dealloc, such as saving its state to disk or log something? How can I make sure that code gets called?
Persistency management should not be tied to
dealloc. If you want to save object state, you should have some kind of session object that will collect the dirty objects and save the changes once in a while or when the application terminates/goes into background.An example using application settings: Let’s say you don’t want to use
NSUserDefaultsfor you application’s settings, maybe because you have some extra logic to do. You have aSettingsclass that keeps all the settings and obviously you would like to keep the changes persisted.You could stuff all the persistency logic into the
Settingsclass, but that violates the single responsibility principle. (= There are good reasons why this would cause you pain.) So you could add aSessionclass that will take of persisting the changes made inSettings.When the application starts you will create an instance of the
Sessionand ask forSettings:Now if there is a file on the disk that contains saved settings, the session will load it (which is simple, as the
Settingsclass implementsNSCoding). If not, the session will create a freshSettingsinstance and return that. In addition, the session will probably start watching for changes in the returnedSettingsinstance, say usingNSNotificationCenter. (It’s quite natural that aSettingsobject would fire a notification when the settings change.)Now when you change something inside a
Settingsinstance that you got from the session, the session will notice that and it will save the changes to disk. Which should be trivial, sinceSettingsimplementNSCoding. You could also mark the object as dirty and only save the changes every few seconds, which is a better solution in case you update the object quite frequently. In that case you might also want to force-save the session when the application is going to terminate or is going background.I’m not saying this scenario is perfect, but it’s certainly better than objects that persist themselves in dealloc 🙂