method_exchangeImplementations注解
method_exchangeImplementations(<#Method _Nonnull m1#>, <#Method _Nonnull m2#>)
//method_exchangeImplementations来把一个方法与另外一个方法进行交换。
先看代码如下:
演示用的Person类
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(nonatomic, assign) NSInteger age;
@property(nonatomic, copy) NSString * name;
+(Person *)sharedManager;
- (instancetype)init;
+ (void) printDZ;
- (void) printDZL;
@end
import "Person.h"
@interface Person ()
@property(nonatomic, strong) NSString * sex;
@end
@implementation Person
+(Person *)sharedManager {
static Person *sharedManager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedManager = [[Person alloc] init];
});
return sharedManager;
}
- (instancetype)init {
self = [super init];
if (self) {
self.sex = @"---女--";
self.age = 10;
self.name = @"布兰妮";
}
return self;
}
+ (void)printDZ
{
// NSLog(@"this is a class method for %@",NSStringFromClass([self class]));
NSLog(@"this is a class method from %@",NSStringFromSelector(_cmd));
}
- (void)printDZL {
NSLog(@"this is a instance method from %@",NSStringFromSelector(_cmd));
// NSLog(@"this is a instance method for %@",NSStringFromClass([self class]));
}
@end
测试代码:
#import "ViewController.h"
#import "Person.h"
#import <objc/runtime.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Person *p1 = [Person new];
Method m1 = class_getClassMethod([Person class],@selector(printDZ));
Method m2 = class_getInstanceMethod([p1 class], @selector(printDZL));
NSLog(@"测试前");
[Person printDZ];
[p1 printDZL];
method_exchangeImplementations(m1, m2);
NSLog(@"测试后:");
[Person printDZ];
[p1 printDZL];
}
@end
打印结果:
方法的初步运用很简单,就不加多做解释了,只要敲一遍,立马就懂了
网友评论