美文网首页
runtime更换系统的方法

runtime更换系统的方法

作者: 大虾咪 | 来源:发表于2017-03-13 15:07 被阅读8次

//

//  NSObject+Until.m

//  替换系统的方法

//

//  Created by 大虾咪 on 2017/3/13.

//  Copyright © 2017年 大虾咪. All rights reserved.

//

#import "NSObject+Until.h"

@implementation NSObject (Until)

+ (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, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)))

{

class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));

} else {

method_exchangeImplementations(originalMethod, swizzledMethod);

}

return YES;

}

@end

相关文章

网友评论

      本文标题:runtime更换系统的方法

      本文链接:https://www.haomeiwen.com/subject/cdafnttx.html