Runtime方法的使用—Class篇

二十一世纪最贵的是什么? ————————————— 答案:人才or房子


完整代码在这里

本篇主要是各种Class相关方法的实现,还有两种运行时调用方法的实现

- (void)viewDidLoad {
    [super viewDidLoad];
    // 调用方法方案1
//    objc_msgSend(self,@selector(initial:),@"完成初始化");
    // 调用方法方案2
    Method method = [self class_getInstanceMethod:SelfClass selector:@selector(initial:)];
    [self method_invoke:self method:method];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Initialize
- (void)initial:(NSString *)str{
    if (str) NSLog(@"%@",str);
    _person = [[Person alloc] init];
    _person.name = @"xietao";
    _person.age = @"18";
    _person.gender = @"male";
    _person.city = @"shanghai";

    [self logRunTimeAction:nil];
}

#pragma mark - IBAction
- (IBAction)logRunTimeAction:(id)sender {
    objc_property_attribute_t attrs[] = { { "T", "@\"NSString\"" }, { "&", "N" }, { "V", "" } };

    size_t objSize = class_getInstanceSize([_person class]);
    size_t allocSize = 2 * objSize;
    uintptr_t ptr = (uintptr_t)calloc(allocSize, 1);


    // Class
    [self class_getClassName:SelfClass];
    [self class_getSuperClass:SelfClass];
    [self class_getInstanceSize:SelfClass];
    [self class_getInstanceVariable:SelfClass name:"_person"];
    [self class_getClassVariable:SelfClass name:"Person"];
    [self class_getInstanceMethod:SelfClass selector:@selector(class_getInstanceMethod:selector:)];
    [self.class class_getClassMethod:SelfClass selector:@selector(class_getClassMethod:selector:)];
    [self class_getProperty:SelfClass name:"person"];
    [self class_getMethodImplementation:SelfClass selector:@selector(class_getMethodImplementation:selector:)];
    [self class_getMethodImplementation_stret:SelfClass selector:@selector(class_getMethodImplementation_stret:selector:)];
    [self class_copyIvarList:[_person class]];
    [self class_copyPropertyList:[_person class]];
    [self class_copyMethodList:[_person class]];
    [self class_copyProtocolList:[_person class]];
    [self class_addIvar:[_person class] name:"country" size:sizeof(NSString *) alignment:0 types:"@"]; // 无效方法
    [self class_addProperty:[_person class] name:"country" attributes:nil attributeCount:3];
    [self class_addMethod:SelfClass selector:NSSelectorFromString(@"runtimeTestMethod:") imp:nil types:"v@:@"];
    [self class_addProtocol:[_person class] protocol:@protocol(RuntimeBaseProtocol)];
    [self class_replaceProperty:[_person class] name:"country" attributes:nil attributeCount:3];
    [self class_replace
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值