How to quit an iPhone app nicely?

早过忘川 提交于 2020-01-10 03:15:07

问题


or "How to simulate a home button pressed event?"

I need to restart my iPhone app, and I want the program to quit, so the user will only have to start it.

If I simply use exit(0) some changes won't get saved, as they would if the user quits by pressing the home button.

The restart needed for language change.

Related code:

- (void)onChangeLanguage: (id)sender {
    NSArray *lang = [NSArray arrayWithObjects:((Whatever *)sender).newLanguage, nil];
    [[NSUserDefaults standardUserDefaults] setObject:lang forKey:@"AppleLanguages"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
    NSString *currentLanguage = [languages objectAtIndex:0];

    NSLog(@"Current language: %@", currentLanguage);
    // ***
}   

If the user restarts using the home button, language will change.

If // *** is replaced by exit(0), the language won't change.


回答1:


I think it’s perfectly fine to call exit, just call [[NSUserDefaults standardUserDefaults] synchronize] before you do that. You can read about the synchronize method in the Apple Documentation:

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.




回答2:


Calling exit(0) is the only legal (but highly not recommended) way to exit the program from your code.
As a possible workaround you can show UIAlertView with no buttons that cannot be dismissed (forcing user to quit your program manually) and telling the user that he has to do that to apply your changes.




回答3:


It's worth noting that there's a private API call, too. Of course, all the usual warnings about using private APIs apply.

[[UIApplication sharedApplication] terminate];



来源:https://stackoverflow.com/questions/1707685/how-to-quit-an-iphone-app-nicely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!