How to change the Application Delegate class?

2020-07-06 07:24发布

问题:

In every iOS app there is an App Delegate class, meaning one of the classes in the app has to implement the delegate methods for the application events such as didFinishLaunching: and so forth. Usually the class name contains "AppDelegate".

The App Delegate class is a subclass of UIApplicationDelegate on iOS or NSApplicationDelegate on the Mac.

class AppDelegate: UIApplicationDelegate {

}

Let's say I want to implement the App Delegate methods in a different class than the original one Xcode created and named for me. How can I do that?

回答1:

You can do the same by modifying the parameters to the UIApplicationMain function present in the main.m file:

UIApplicationMain(argc,argv,nil,nil);

The last parameter takes the name of the class which is implementing the UIApplicationDelegate protocol.

So the default implementation looks something like:

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;

After modifying it will be something like:

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, NSStringFromClass([< Your class name will go here > class]));
[pool release];
return retVal;


回答2:

I achieved this in Swift by changing the AppDelegate's default template implementation:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

replace with:

import UIKit

@UIApplicationMain
class MyAppAppDelegate: UIResponder, UIApplicationDelegate {

See the new class name.



标签: iphone ios xcode