iOS 強制退出程序APP代碼
1、先po代碼
// 退出程序 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
UIAlertView* alert = [[UIAlertView alloc] initWithTitle: self .exitapplication message:@ "" delegate: self cancelButtonTitle: self .exityes otherButtonTitles: self .exitno, nil ];
[alert show]; - ( void )alertView:(UIAlertView *)alertView clickedButtonAtIndex:( NSInteger )buttonIndex
{
if (buttonIndex ==0){
[ self exitApplication ];
}
}
- ( void )exitApplication {
AppDelegate *app = [UIApplication sharedApplication].delegate;
UIWindow *window = app.window; // 動畫 1
[UIView animateWithDuration:1.0f animations:^{
window.alpha = 0;
window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
} completion:^( BOOL finished) {
exit(0);
}];
//exit(0);
}
|
退出程序 2: //-------------------------------- 退出程序 2-----------------------------------------// - (void)exitApplication { [UIView beginAnimations:@"exitApplication" context:nil]; [UIView setAnimationDuration:0.5]; [UIView setAnimationDelegate:self]; // [UIView setAnimationTransition:UIViewAnimationCurveEaseOut forView:self.view.window cache:NO]; [UIView setAnimationTransition:UIViewAnimationCurveEaseOut forView:self.window cache:NO]; [UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)]; //self.view.window.bounds = CGRectMake(0, 0, 0, 0); self.window.bounds = CGRectMake(0, 0, 0, 0); [UIView commitAnimations]; } - (void)animationFinished:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { if ([animationID compare:@"exitApplication"] == 0) { exit(0); } }
2、程序中的exit(1)、abort()、assert(0);
先來看一下程序的死亡方式:
程序的死亡大致有三種:自然死亡,即無疾而終,通常就是main()中的一個return 0;自殺,當程序發現自己再活下去已經沒有任何意義時,通常會選擇自殺。當然,這種自殺也是一種請求式的自殺,即請求OS將自己斃掉。有三種方式:void exit(int status)和void abort(void)、assert(condition)。他殺,同現實不同的是,程序家族中的他殺行徑往往是由自己至親完成的,通常這個至親就是他的生身父親(還是母親?)。語言本身並沒有提供他殺的兇器,這些兇器往往是由OS直接或者間接(通過一些進程庫,如pthread)提供的。 自然死是最完美的結局,他殺是我們最不願意看到的,自殺雖是迫不得已,但主動權畢竟還是由程序自己掌控的;abort被調用時,程序將直接退出,任何對象的析構函數都不會調用
介紹:
abort: 這是默認的程序結束函數,這種方式可能會或可能不會以刷新與關閉打開的文件
或刪除臨時文件,這與你的設計有關.
exit: 附加了關閉打開文件與返回狀態碼給執行環境,並調用你用atexit註冊的返回函數
assert(1)為oc中的宏,只在debug模式下有用,當條件成立時,程序不會終止掉;當條件不成立時,程序終止。
so,oc程序中建議用assert(condition)函數。
3、選擇
Q:怎樣用代碼方式退出iOS程序
A:沒有提供用於正常退出IOS應用的API。
在IOS中,用戶點擊Home鍵來關閉應用。你的應用應該符合以下條件:它不能自行調用方法,而應采取措施與用戶交互,表明問題的性質和應用可能會采取的行為,比如打開WIFI,使用定位服務等供用戶選擇確定使用;
警告:不要使用exit函數,調用exit會讓用戶感覺程序崩潰了,不會有按Home鍵返回時的平滑過渡和動畫效果;另外,使用exit可能會丟失數據,因為調用exit並不會調用-applicationWillTerminate:方法和UIApplicationDelegate方法;
如果在開發或者測試中確實需要強行終止程序時,推薦使用abort 函數和assert宏;
iOS 強制退出程序APP代碼