本篇将介绍了Hello World程序的分析代码,也就是到底这个程序是怎么say Hello的.本文非常适合尚未入门的开发者,希望各位iPhone应用程序开发的初学者喜欢。
每个学习程序开发的第一个程序都是“Hello World”,作为刚刚入门的iPhone应用程序开发者,掌握“Hello World”的分析代码是十分重要的。本篇将介绍了Hello World程序的分析代码,也就是到底这个程序是怎么say Hello的。
这个程序基本的运行顺序是:载入窗口(UIWindow)->载入自定义的界面(MyViewController),而各种消息的处理均在自定义的界面当中.而程序的设计遵循了MVC(Model-View-Controller)方法,也就是界面和程序是分开做的,通过controller联接彼此
首先看窗口.在 HelloWorldAppDelegate.h 文件当中有这样两行:
其中第一行定义了程序的窗口,第二行定义了我们自己的界面.在 HelloWorldAppDelegate.m 文件中,函数
- IBOutletUIWindow*window;
- MyViewController*myViewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application 是iPhone开发者经常要打交道的一个,定义了程序启动后要做的工作.这几行程序的任务是:指定 myViewController 为子界面,
- MyViewController* aViewController =[[MyViewControlleralloc]initWithNibName:@”HelloWorld”bundle:[NSBundlemainBundle]];
- self.myViewController = aViewController ;
- [aViewControllerrelease];
并把子界面显示到上面来.
- UIView* controllersView =[myViewControllerview];
- [windowaddSubview:controllersView];
- [windowmakeKeyAndVisible];
前面提到了,程序设计遵循了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*)toucheswithEvent:(UIEvent*)event
- {
- //Dismissthekeyboardwhentheviewoutsidethetextfieldistouched.
- [textFieldresignFirstResponder];
- //Revertthetextfieldtothepreviousvalue.
- textField.text = self .string;
- [supertouchesBegan:toucheswithEvent:event];
- }
的作用是:对触摸做出响应.当触摸在键盘外时,通过 resignFirstResponder 撤销键盘.
- -(BOOL)textFieldShouldReturn:(UITextField*)theTextField{
- //Whentheuserpressesreturn,takefocusawayfromthetextfieldsothatthekeyboardisdismissed.
- if( theTextField ==textField){
- [textFieldresignFirstResponder];
- //Invokethemethodthatchangesthegreeting.
- [selfupdateString];
- }
- returnYES;
- }
作用是:当输入完文字并按Return后,隐藏键盘,并调用updateString命令来更新显示.这个命令如下:
- -(void)updateString{
- //Storethetextofthetextfieldinthe‘string’instancevariable.
- self.string = textField .text;
- //Setthetextofthelabeltothevalueofthe‘string’instancevariable.
- label.text = self .string;
- }
简单的说就是用输入的文字来替换标签原来的文字以更新显示.
好了,关于Hello World的分析代码就介绍到这,主要语句的功能都解说到了.希望大家喜欢。