Skip to content

Instantly share code, notes, and snippets.

@Daij-Djan
Last active February 2, 2018 10:29
Show Gist options
  • Save Daij-Djan/4969809 to your computer and use it in GitHub Desktop.
Save Daij-Djan/4969809 to your computer and use it in GitHub Desktop.
universal main.m for iOS and OSX with or without ARC. It checks the info.plist and invokes apple's native `UIApplicationMain` or `NSApplicationMain` with the right parameters in any case. (See Comment for more info)
//
// main.m
//
// Created by Dominik Pich on 10.02.13.
// Everybody is free to use this however they want!
//
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#import <Cocoa/Cocoa.h>
#endif
#define kDDAppDelegateClassKey @"DDAppDelegateClass"
#define kNSMainNibFileKey @"NSMainNibFile"
#define kNSPrincipalClassKey @"NSPrincipalClass"
#if TARGET_OS_IPHONE
#define kNSPrincipalClassDefault @"UIApplication"
#else
#define kNSPrincipalClassDefault @"NSApplication"
#endif
id DDAppDelegate = nil;//arc releases this too early if we make it a stack var
int main(int argc, char *argv[])
{
int status = -1;
#if !__has_feature(objc_arc)
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
#else
@autoreleasepool
#endif
{
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
NSString *appDelegateClassName = [infoDict objectForKey:kDDAppDelegateClassKey];
NSString *nibName = [infoDict objectForKey:kNSMainNibFileKey];
NSString *principalClassName = [infoDict objectForKey:kNSPrincipalClassKey];
BOOL hasAppDelegateClassName = appDelegateClassName.length;
BOOL hasNibName = nibName.length;
BOOL hasCustomPrincipalClassName = (principalClassName.length && ![principalClassName isEqualToString:kNSPrincipalClassDefault]);
assert((hasAppDelegateClassName || hasNibName || hasCustomPrincipalClassName) && "need to specify EITHER a xib file (via NSMainNibFile key) OR a class name to use as delegate for the application (via DDAppDelegateClass key) OR the name of the custom principal class (via NSPrincipalClass key)");
#if TARGET_OS_IPHONE
status = UIApplicationMain(argc, argv, principalClassName, appDelegateClassName);
#else
id appDelegate = nil;
if(hasAppDelegateClassName) {
Class appDelegateClass = NSClassFromString(appDelegateClassName);
DDAppDelegate = [[appDelegateClass alloc] init];
[[NSApplication sharedApplication] setDelegate:DDAppDelegate];
}
status = NSApplicationMain(argc, (const char **)argv);
#if !__has_feature(objc_arc)
[appDelegate autorelease];
#endif
appDelegate = nil;
#endif
}
#if !__has_feature(objc_arc)
[pool drain];
#endif
return status;
}
@Daij-Djan
Copy link
Author

fixed an arc issue

@andreyugolnik
Copy link

andreyugolnik commented Feb 2, 2018

Why you declare id appDelegate = nil? In which case it used?
I think DDAppDelegate should be used instead appDelegate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment