Last active
December 12, 2015 02:48
-
-
Save xlc/4701043 to your computer and use it in GitHub Desktop.
how to create instance even alloc return nil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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