Skip to content

Instantly share code, notes, and snippets.

@MP0w
Created July 4, 2014 17:46
Show Gist options
  • Save MP0w/f100cdb98106464cce1c to your computer and use it in GitHub Desktop.
Save MP0w/f100cdb98106464cce1c to your computer and use it in GitHub Desktop.
swizzle tests
//
// main.m
// swizzle
//
// Created by Alex Manzella on 04/07/14.
// Copyright (c) 2014 mpow. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface MPResponder : NSObject
@end
@implementation MPResponder
- (NSInteger)plusplus:(NSInteger)number{
NSLog(@"orig %@",NSStringFromSelector(_cmd));
return number+1;
}
@end
@interface MPView : MPResponder
@end
@implementation MPView
@end
@interface MPView (swizzling)
@end
@implementation MPView (swizzling)
static IMP defaultIMP;
+ (void)load{
NSLog(@"swizzling");
defaultIMP = class_getMethodImplementation(self, @selector(plusplus:));
IMP newIMP = class_getMethodImplementation(self, @selector(hooked_plusplus:));
method_setImplementation(class_getInstanceMethod(self, @selector(plusplus:)), newIMP);
}
- (NSInteger)hooked_plusplus:(NSInteger)number{
NSLog(@"swizzling %@",NSStringFromSelector(_cmd));
number = (NSInteger)defaultIMP(self,_cmd,number);
return number+2;
}
@end
@interface MPView (swizzlingagain)
@end
@implementation MPView (swizzlingagain)
static IMP hookedOnlyOnceIMP;
+ (void)load{
NSLog(@"swizzling again");
hookedOnlyOnceIMP = class_getMethodImplementation(self, @selector(plusplus:));
IMP newIMP = class_getMethodImplementation(self, @selector(againhooked_plusplus:));
method_setImplementation(class_getInstanceMethod(self, @selector(plusplus:)), newIMP);
}
- (NSInteger)againhooked_plusplus:(NSInteger)number{
NSLog(@"swizzlingagain %@",NSStringFromSelector(_cmd));
number = (NSInteger)hookedOnlyOnceIMP(self,_cmd,number);
return number+2;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
MPView* view=[[MPView alloc] init];
NSLog(@"number %li",(long)[view plusplus:10]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment