iPhone開發(fā)入門篇 “Hello World”分析代碼
每個學(xué)習(xí)程序開發(fā)的第一個程序都是“Hello World”,作為剛剛?cè)腴T的iPhone應(yīng)用程序開發(fā)者,掌握“Hello World”的分析代碼是十分重要的。本篇將介紹了Hello World程序的分析代碼,也就是到底這個程序是怎么say Hello的。
51CTO推薦專題:iPhone應(yīng)用程序開發(fā)初探
這個程序基本的運行順序是:載入窗口(UIWindow)->載入自定義的界面(MyViewController),而各種消息的處理均在自定義的界面當(dāng)中.而程序的設(shè)計遵循了MVC(Model-View-Controller)方法,也就是界面和程序是分開做的,通過controller聯(lián)接彼此.
首先看窗口.在 HelloWorldAppDelegate.h 文件當(dāng)中有這樣兩行:
- IBOutlet UIWindow *window;
- MyViewController *myViewController;
其中第一行定義了程序的窗口,第二行定義了我們自己的界面.在 HelloWorldAppDelegate.m 文件中,函數(shù)
- (void)applicationDidFinishLaunching:(UIApplication *)application 是iPhone開發(fā)者經(jīng)常要打交道的一個,定義了程序啟動后要做的工作.這幾行程序的任務(wù)是:指定 myViewController 為子界面,
- MyViewController *aViewController = [[MyViewController alloc] initWithNibName:@”HelloWorld” bundle:[NSBundle mainBundle]];
- self.myViewController = aViewController;
- [aViewController release];
并把子界面顯示到上面來.
- UIView *controllersView = [myViewController view];
- [window addSubview:controllersView];
- [window makeKeyAndVisible];
前面提到了,程序設(shè)計遵循了MVC方法,但我們還沒介紹代碼和界面之間是怎么聯(lián)系的,也就是說,我們說了程序的UIWindow和view controller要干什么什么,也畫出了界面,可iPhone怎么知道哪個類對應(yīng)哪個界面呢?這個是在IB(Interface Builder)中完成的.請雙擊 HelloWorld.xib 打開IB.下面看的就是我們的界面.
點到File’s Owner,在Identity Viewer中,注意Class為MyViewController,這就定義了Model和View之間的對應(yīng)關(guān)系.在同一個xib文件中,File’s Owner設(shè)定為一個類,并指向其View,該對應(yīng)關(guān)系就建立好了.
在 MyViewController.m 文件中,
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- {
- // Dismiss the keyboard when the view outside the text field is touched.
- [textField resignFirstResponder];
- // Revert the text field to the previous value.
- textField.text = self.string;
- [super touchesBegan:touches withEvent:event];
- }
的作用是:對觸摸做出響應(yīng).當(dāng)觸摸在鍵盤外時,通過 resignFirstResponder 撤銷鍵盤.
- - (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
- // When the user presses return, take focus away from the text field so that the keyboard is dismissed.
- if (theTextField == textField) {
- [textField resignFirstResponder];
- // Invoke the method that changes the greeting.
- [self updateString];
- }
- return YES;
- }
作用是:當(dāng)輸入完文字并按Return后,隱藏鍵盤,并調(diào)用updateString命令來更新顯示.這個命令如下:
- - (void)updateString {
- // Store the text of the text field in the ‘string’ instance variable.
- self.string = textField.text;
- // Set the text of the label to the value of the ‘string’ instance variable.
- label.text = self.string;
- }
簡單的說就是用輸入的文字來替換標(biāo)簽原來的文字以更新顯示.
好了,關(guān)于Hello World的分析代碼就介紹到這,主要語句的功能都解說到了.希望大家喜歡。
本文選自淫雨霏霏的博客:http://lichen1985.com/blog/
【編輯推薦】
- 深入iPhone開發(fā):應(yīng)用程序核心探秘
- iPhone內(nèi)存管理面面觀 對象所有權(quán)與引用計數(shù)
- 專訪最牛iPhone開發(fā)團(tuán)隊:走進(jìn)移動開發(fā)
- iPad軟件設(shè)計初步:它不只是大號的iPhone