Created
August 16, 2012 22:37
-
-
Save alts/3374270 to your computer and use it in GitHub Desktop.
swizzling class for oBj-c
This file contains hidden or 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
// | |
// Swizzler.m | |
// ZombieFarm | |
// | |
// Created by Stephen Altamirano on 8/16/12. | |
// Copyright (c) 2012 playforge. All rights reserved. | |
// | |
#import <objc/runtime.h> | |
#import "Swizzler.h" | |
// hidden class | |
@interface SwizzleState : NSObject | |
- (id)initWithMethod:(Method)m implementation:(IMP)i; | |
- (void)revert; | |
@end | |
@implementation SwizzleState | |
{ | |
Method originalMethod; | |
IMP originalImplementation; | |
} | |
- (id)initWithMethod:(Method)m implementation:(IMP)i | |
{ | |
if (self = [super init]) | |
{ | |
originalMethod = m; | |
originalImplementation = i; | |
} | |
return self; | |
} | |
- (void)revert | |
{ | |
method_setImplementation(originalMethod, originalImplementation); | |
} | |
@end | |
@implementation Swizzler | |
{ | |
NSMutableArray* history; | |
} | |
- (void)replaceClassMethod:(SEL)action | |
forClass:(Class)target | |
fromClass:(Class)source | |
{ | |
Method originalMethod = class_getClassMethod(target, action); | |
IMP originalImplementation = method_getImplementation(originalMethod); | |
Method replacementMethod = class_getClassMethod(source, action); | |
IMP replacementImplementation = method_getImplementation(replacementMethod); | |
method_setImplementation(originalMethod, replacementImplementation); | |
SwizzleState* state = [[SwizzleState alloc] initWithMethod:originalMethod | |
implementation:originalImplementation]; | |
[history addObject:[state autorelease]]; | |
} | |
- (void)replaceInstanceMethod:(SEL)action | |
forClass:(Class)target | |
fromClass:(Class)source | |
{ | |
Method originalMethod = class_getInstanceMethod(target, action); | |
IMP originalImplementation = method_getImplementation(originalMethod); | |
Method replacementMethod = class_getInstanceMethod(source, action); | |
IMP replacementImplementation = method_getImplementation(replacementMethod); | |
method_setImplementation(originalMethod, replacementImplementation); | |
SwizzleState* state = [[SwizzleState alloc] initWithMethod:originalMethod | |
implementation:originalImplementation]; | |
[history addObject:[state autorelease]]; | |
} | |
- (void)undoReplacements | |
{ | |
SwizzleState* state; | |
for (int i = [history count] - 1, l = 0; i >= l; i--) | |
{ | |
state = [history objectAtIndex:i]; | |
[state revert]; | |
} | |
[history removeAllObjects]; | |
} | |
- (void)dealloc | |
{ | |
[self undoReplacements]; | |
[history release]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment