创建一个OC项目,
创建项目 目录结构
对象方法调用源码如下:
main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#include <objc/message.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Person *p = [[Person alloc]init];
[p run];
objc_msgSend(p, sel_registerName("run"));
}
return 0;
}
Person.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Person : NSObject
- (void) run;
@end
NS_ASSUME_NONNULL_END
Person.m
#import "Person.h"
@implementation Person
- (void)run{
NSLog(@"hellow its me");
}
@end
切记。一定关闭
关闭严格交验项目跑起来
日志输出
2019-08-15 23:43:25.320375+0800 RuntimeC[4896:98306] hellow its me
2019-08-15 23:43:25.320775+0800 RuntimeC[4896:98306] hellow its me
Program ended with exit code: 0
可以看到,objc_msgSend达到了调用方法的作用。
我们在main.m添加打印指针
NSLog(@"%p -- %p", sel_registerName("run"),@selector(run));
输出如下:
2019-08-15 23:50:06.446510+0800 RuntimeC[5052:102860] 0x7fff4e7f3c7e -- 0x7fff4e7f3c7e
一摸一样
类方法调用源码如下:
Person.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Person : NSObject
- (void) run;
+ (void)walk;
@end
NS_ASSUME_NONNULL_END
Person.m:
#import "Person.h"
@implementation Person
- (void)run{
NSLog(@"hellow its me");
}
+ (void)walk{
NSLog(@"%s",__func__);
}
@end
main.m:
#import <Foundation/Foundation.h>
#import "Person.h"
#include <objc/message.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
objc_msgSend(objc_getClass("Person"), sel_registerName("walk"));
}
return 0;
}
日志输出:
2019-08-20 01:23:22.873399+0800 RuntimeC[6287:175703] +[Person walk]
Program ended with exit code: 0
网友评论