如何完美退出 iPhone 应用程序?
或“如何模拟主页按钮按下事件?”
我需要重新启动我的 iPhone 应用程序,并且我希望该程序退出,因此用户只需启动它即可。
如果我只是使用 exit(0)
,某些更改将不会被保存,就像用户通过按主页按钮退出一样。
更改语言需要重新启动。
相关代码:
- (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);
// ***
}
如果用户使用主页按钮重新启动,语言将会改变。
如果将 // ***
替换为 exit(0)
,则语言不会改变。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调用
exit(0)
是从代码中退出程序的唯一合法(但强烈不推荐)的方法。作为一种可能的解决方法,您可以显示没有无法关闭的按钮的 UIAlertView(强制用户手动退出程序),并告诉用户他必须这样做才能应用您的更改。
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.
我认为调用
exit
是完全可以的,只需在执行此操作之前调用[[NSUserDefaults standardUserDefaults] Synchronize]
即可。您可以在 Apple 文档:I think it’s perfectly fine to call
exit
, just call[[NSUserDefaults standardUserDefaults] synchronize]
before you do that. You can read about thesynchronize
method in the Apple Documentation:值得注意的是,还有一个私有 API 调用。当然,所有有关使用私有 API 的常见警告都适用。
[[UIApplication共享应用程序]终止];
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];