开发者

applicationWillTerminate, delegate or view?

开发者 https://www.devze.com 2022-12-22 14:15 出处:网络
I am looking to save some settings when my application exits and I am a little confused about the 2 different versions b开发者_如何转开发elow. My feeling is that to better fit the MVC pattern I should

I am looking to save some settings when my application exits and I am a little confused about the 2 different versions b开发者_如何转开发elow. My feeling is that to better fit the MVC pattern I should be using the version in the viewController. I am just curious as most folks don't seem to do much in the appDelegate when that call would be used?

AppDelegate

-(void)applicationWillTerminate:(UIApplication *)application {
    NSLog(@"_deli: applicationWillTerminate");
}

ViewController

-(void)applicationWillTerminate:(NSNotification *)notification {
    NSLog(@"_view: applicationWillTerminate");
}

many thanks

EDIT_001:

Sorry, I should claifiy, you would also need to add (see below) to the ViewController to make the above work.

UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillTerminate:)
                                                 name:UIApplicationWillTerminateNotification 
                                               object:app];

gary


Use whichever one has access to the data you want to save. So if the ViewController can see the data but the AppDelegate can't, use that.


Well, to flog my personal hobby horse, I would say that settings are a form of preferences that should be saved in a dedicated data model. NSUserDefaults, for example, is a data model built on the singleton pattern. You could, of course roll your own. There is no problem with having multiple data models in the same app if they manage unrelated information.

The key is to save defaults/preference/state as they are made. Then when the application quits the defaults are already automatically saved. Remember that on the iPhone you never know when the app will be interrupted or quit. Save as you go is really the only option.

Also, in the code examples you provided, how will the view controller know when the application quits? IIRC, UIViewController does not have a applicationWillTerminate: method and does not automatically receive a specific app will quit message. (Edit: In the comments, KennyTM points out that the view controller can register and listen for UIApplicationWillTerminateNotification) You would have to put this functionality in -viewWillUnload. Otherwise, you would have to track your view controllers from the app delegate have the delegate send the active view controller a message when the app quit.

0

精彩评论

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