Created
October 24, 2016 07:41
-
-
Save wanyakun/3af382fd0b0dc08cc6788e775e53f4a7 to your computer and use it in GitHub Desktop.
NSObject+Swizzle
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
// | |
// NSObject+Swizzle.h | |
// CrashDemo | |
// | |
// Created by wanyakun on 16/7/5. | |
// Copyright © 2016年 com.ucaiyuan. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSObject (Swizzle) | |
/** | |
* 对系统方法进行替换 | |
* | |
* @param originalSelector 被替换的方法 | |
* @param swizzledSelector 实际使用的方法 | |
* @param error 替换过程中出现的错误,如果没有错误则为nil | |
* | |
* @return 是否替换成功 | |
*/ | |
+ (BOOL)swizzleMethod:(SEL)originalSelector withMethod:(SEL)swizzledSelector error:(NSError **)error; | |
@end |
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
// | |
// NSObject+Swizzle.m | |
// CrashDemo | |
// | |
// Created by wanyakun on 16/7/5. | |
// Copyright © 2016年 com.ucaiyuan. All rights reserved. | |
// | |
#import "NSObject+Swizzle.h" | |
#import <objc/runtime.h> | |
@implementation NSObject (Swizzle) | |
+ (BOOL)swizzleMethod:(SEL)originalSelector withMethod:(SEL)swizzledSelector error:(NSError **)error { | |
Method originalMethod = class_getInstanceMethod(self, originalSelector); | |
if (!originalMethod) { | |
NSString *string = [NSString stringWithFormat:@"%@ 类没有找到 %@ 方法", NSStringFromClass([self class]), NSStringFromSelector(originalSelector)]; | |
*error = [NSError errorWithDomain:@"NSCocoaErrorDomain" code:-1 userInfo:[NSDictionary dictionaryWithObject:string forKey:NSLocalizedDescriptionKey]]; | |
return NO; | |
} | |
Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector); | |
if (!swizzledMethod) { | |
NSString *string = [NSString stringWithFormat:@"%@ 类没有找到 %@ 方法", NSStringFromClass([self class]), NSStringFromSelector(swizzledSelector)]; | |
*error = [NSError errorWithDomain:@"NSCocoaErrorDomain" code:-1 userInfo:[NSDictionary dictionaryWithObject:string forKey:NSLocalizedDescriptionKey]]; | |
return NO; | |
} | |
if (class_addMethod([self class], originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))) { | |
class_replaceMethod([self class], swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); | |
} else { | |
method_exchangeImplementations(originalMethod, swizzledMethod); | |
} | |
return YES; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment