Skip to content

Instantly share code, notes, and snippets.

@xlc
Last active December 12, 2015 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xlc/4701043 to your computer and use it in GitHub Desktop.
Save xlc/4701043 to your computer and use it in GitHub Desktop.
how to create instance even alloc return nil
#import "AppDelegate.h"
#import <objc/runtime.h>
#import <objc/message.h>
@interface Test : NSObject
@end
@implementation Test
+ (id)alloc {
return nil;
}
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
id test = [Test alloc];
NSLog(@"%@", test); // (null)
// 1. use objc_msgSendSuper to call [NSObject alloc]
id metaclass = objc_getMetaClass("NSObject");
struct objc_super superstruct = {[Test class], metaclass};
id obj = objc_msgSendSuper(&superstruct, @selector(alloc));
NSLog(@"%@", obj); // <Test: 0x751dae0>
// 2. just call IMP of [NSObject alloc]
IMP allocimp = [NSObject methodForSelector:@selector(alloc)];
id obj2 = allocimp([Test class], @selector(alloc));
NSLog(@"%@", obj2); // <Test: 0x712e6f0>
return YES;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment