.h文件
//
// RuntimeTest.h
// charReverse
//
// Created by huant on 2019/3/22.
// Copyright © 2019 huant. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface RuntimeTest : NSObject
- (void)test:(NSString*)str;
@end
NS_ASSUME_NONNULL_END
.m文件(resolveInstanceMethod方法里,动态添加方法实现)
//
// RuntimeTest.m
// charReverse
//
// Created by huant on 2019/3/22.
// Copyright © 2019 huant. All rights reserved.
//
#import "RuntimeTest.h"
#import <objc/runtime.h>
@implementation RuntimeTest
void eat(id selfName, SEL _cmdName, NSString *param){
NSLog(@"调用eat 参数:1%@ 参数2:%@ 参数3:%@",selfName,NSStringFromSelector(_cmdName),param);
NSLog(@"%s", __func__);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel{
if (sel == @selector(test:)) {
NSLog(@"%s", __func__);
BOOL isSuccess = class_addMethod(self, sel, (IMP)eat, "v@::");
NSLog(@" 是否添加成功:%d", isSuccess);
return isSuccess;
}else{
return [super resolveInstanceMethod:sel];
}
}
- (id)forwardingTargetForSelector:(SEL)aSelector{
NSLog(@"%s", __func__);
return nil;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
if (aSelector == @selector(test:)) {
NSLog(@"%s", __func__);
return [NSMethodSignature signatureWithObjCTypes:"v@::"];
}else{
return [super methodSignatureForSelector:aSelector];
}
}
- (void)forwardInvocation:(NSInvocation *)anInvocation{
NSLog(@"%s", __func__);
}
@end
调用
- (void)viewDidLoad {
[super viewDidLoad];
RuntimeTest * test = [RuntimeTest new];
[test test:@"小猫"];
}
网友评论