开发者

How to make sure your dealloc code is called on application termination?

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 mo开发者_运维问答re 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 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 :-)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜