views:

44

answers:

2

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?

+4  A: 

Make sure the object gets released in your applicationWillTerminate: (NSApplicationDelegate).

DarkDust
It doesn't have to be in the delegate. You can observe for `NSApplicationWillTerminateNotification` on the local notification center.
Peter Hosey
+4  A: 

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 NSUserDefaults for you application’s settings, maybe because you have some extra logic to do. You have a Settings class that keeps all the settings and obviously you would like to keep the changes persisted.

You could stuff all the persistency logic into the Settings class, but that violates the single responsibility principle. (= There are good reasons why this would cause you pain.) So you could add a Session class that will take of persisting the changes made in Settings.

When the application starts you will create an instance of the Session and ask for Settings:

Session *session = [[Session alloc] init];
Settings *settings = [session loadSettings];

Now if there is a file on the disk that contains saved settings, the session will load it (which is simple, as the Settings class implements NSCoding). If not, the session will create a fresh Settings instance and return that. In addition, the session will probably start watching for changes in the returned Settings instance, say using NSNotificationCenter. (It’s quite natural that a Settings object would fire a notification when the settings change.)

Now when you change something inside a Settings instance that you got from the session, the session will notice that and it will save the changes to disk. Which should be trivial, since Settings implement NSCoding. 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 :-)

zoul
Could you elaborate on this please? O:-)
Fernando