Search code examples
iostargetappdelegate

How to set different AppDelegate for different targets within same project?


I'm very very new to the target concept in Xcode. I have followed this tutorial to learn to create two targets in the same project. I just want to know how to make target A use AppDelegateA.swift as its designated app delegate, and target B use AppDelegateB.swift as its designated app delegate. Because on the tutorial, it actually teaches how to make two apps from the same AppDelegate. But I make two (almost) completely different apps, that share a lot of resources and libraries.

And while we're on the subject, can I also have target A use a storyboard called Main, and target B also use a storyboard called Main, but they are actually a different storyboard (but put together inside the same project)?


Solution

  • Yes you can create 2 different based upon the target make following changes:

    in the projects

    main.m
    

    you could do something like

    int main(int argc, char *argv[])
    {
        @autoreleasepool {
    
            NSString *appDelegateName;
            if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
                appDelegateName =  NSStringFromClass([AppDelegateIPhone class]);
            } else {
                appDelegateName =  NSStringFromClass([AppDelegateIPad class]);
            }
            return UIApplicationMain(argc, argv, nil, appDelegateName);
        }
    }
    

    But IMO you should not do it.

    Instead doi it as apple does it to, in app delegate load different view controllers or different XIBs.

        @implementation AppDelegate
    
        - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
        {
            self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
            // Override point for customization after application launch.
            if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
                self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil] autorelease];
            } else {
                self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil] autorelease];
            }
            self.window.rootViewController = self.viewController;
            [self.window makeKeyAndVisible];
            return YES;
        }
    
    @end