iPhone開發入門篇 “Hello World”分析代碼
每個學習程序開發的第一個程序都是“Hello World”,作為剛剛入門的iPhone應用程序開發者,掌握“Hello World”的分析代碼是十分重要的。本篇將介紹了Hello World程序的分析代碼,也就是到底這個程序是怎么say Hello的。
51CTO推薦專題:iPhone應用程序開發初探
這個程序基本的運行順序是:載入窗口(UIWindow)->載入自定義的界面(MyViewController),而各種消息的處理均在自定義的界面當中.而程序的設計遵循了MVC(Model-View-Controller)方法,也就是界面和程序是分開做的,通過controller聯接彼此.
首先看窗口.在 HelloWorldAppDelegate.h 文件當中有這樣兩行:
- IBOutlet UIWindow *window;
- MyViewController *myViewController;
其中第一行定義了程序的窗口,第二行定義了我們自己的界面.在 HelloWorldAppDelegate.m 文件中,函數
- (void)applicationDidFinishLaunching:(UIApplication *)application 是iPhone開發者經常要打交道的一個,定義了程序啟動后要做的工作.這幾行程序的任務是:指定 myViewController 為子界面,
- MyViewController *aViewController = [[MyViewController alloc] initWithNibName:@”HelloWorld” bundle:[NSBundle mainBundle]];
- self.myViewController = aViewController;
- [aViewController release];
并把子界面顯示到上面來.
- UIView *controllersView = [myViewController view];
- [window addSubview:controllersView];
- [window makeKeyAndVisible];
前面提到了,程序設計遵循了MVC方法,但我們還沒介紹代碼和界面之間是怎么聯系的,也就是說,我們說了程序的UIWindow和view controller要干什么什么,也畫出了界面,可iPhone怎么知道哪個類對應哪個界面呢?這個是在IB(Interface Builder)中完成的.請雙擊 HelloWorld.xib 打開IB.下面看的就是我們的界面.
點到File’s Owner,在Identity Viewer中,注意Class為MyViewController,這就定義了Model和View之間的對應關系.在同一個xib文件中,File’s Owner設定為一個類,并指向其View,該對應關系就建立好了.
在 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];
- }
的作用是:對觸摸做出響應.當觸摸在鍵盤外時,通過 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;
- }
作用是:當輸入完文字并按Return后,隱藏鍵盤,并調用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;
- }
簡單的說就是用輸入的文字來替換標簽原來的文字以更新顯示.
好了,關于Hello World的分析代碼就介紹到這,主要語句的功能都解說到了.希望大家喜歡。
本文選自淫雨霏霏的博客:http://lichen1985.com/blog/
【編輯推薦】