iOS 应用程序的起点始终是main()
函数(感谢@bogatyr),它通常包含类似的代码,
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
的最后两个参数UIApplicationMain
很重要,指定主体类名和应用程序委托。如果它们是nil
,那么将在主窗口 xib 中查找 Info.plist(通常是MainWindow.xib
)。
// If nil is specified for principalClassName, the value for NSPrincipalClass
// from the Info.plist is used. If there is no NSPrincipalClass key specified, the
// UIApplication class is used. The delegate class will be instantiated
// using init.
.. UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
File Owner 不需要通过 xib 设置,可以直接在这个UIApplicationMain
函数中指定。
principalClassName
可以是字符串UIApplication
或UIApplication
. 同样delegateClassName
可以直接在这个方法中指定。init
正如文档所说,委托类是使用实例化的。假设我们指定我们的委托类 -MyAppDelegate
作为一个字符串,
UIApplicationMain(int argc, char *argv[], nil, @"MyAppDelegate");
首先实例化 UIApplication 的一个实例,然后使用NSClassFromString
我想从这个字符串创建委托类。
一旦委托对象被实例化并且应用程序准备就绪,将使用委托方法通知这个委托对象didFinishLaunchingWithOptions
。
Class delegateClass = NSClassFromString(@"MyAppDelegate");
id <UIApplicationDelegate> delegateObject = [[delegateClass alloc] init];
// load whatever else is needed, then launch the app
// once everything is done, call the delegate object to
// notify app is launched
[delegateObject application:self didFinishLaunchingWithOptions:...];
如果不使用 nib,这就是 UIApplication 以编程方式处理它的方式。在中间使用笔尖并没有太大的不同。