事件驅(qū)動
- APP由一組能夠互相發(fā)送消息的組件構(gòu)成,這些組件大部分由IOS提供,如button/label/viewController等。
- 組件之間通過傳遞消息來進(jìn)行通信,比如上面的例子中,當(dāng)按下button按鈕后,button組件會給view controller發(fā)送消息,然后view controller又會給更多的組件發(fā)送消息。
- ios中的程序都是消息驅(qū)動的,意味著這些組件都要隨時監(jiān)聽事件,一旦有事件發(fā)生,就要執(zhí)行對應(yīng)的動作。在示例APP中,button的TouchUpInside 事件,是與ViewController中的showAlert Action關(guān)聯(lián)的,所以當(dāng)button一旦被Touch,就會發(fā)送showAlert的消息給ViewController。ViewController執(zhí)行ShowAlert,在ShowAlert中viewController會發(fā)送其他消息,如發(fā)送addAction給UIAlertController。
流程解析

消息傳遞圖
- 用戶點擊屏幕
- IOS的UIKit收到這個touchEvent,并將這個TouchEvent傳遞給UIButton。
- 當(dāng)手指從屏幕離開后,touchesEnded將showAlert消息發(fā)送給ViewController。
- viewController中執(zhí)行showAlert函數(shù),這個函數(shù)是彈出警告框,需要將presentViewController這個消息發(fā)送給對應(yīng)的alert 控件(這個控件是動態(tài)創(chuàng)建的)。
- 顯示完畢后返回。
- showAlert函數(shù)返回。
- 返回,繼續(xù)等待下一次event發(fā)生。