iOS 开发:Runtime(详解五)获取类的属性、方法

1. 获取类详细属性、方法简述

在苹果官方为我们提供的类中,只能获取一小部分公开的属性和方法。有些我们恰好需要的属性和方法,可能会被官方隐藏了起来,没有直接提供给我们。
那应该如何才能获取一个类中所有的变量和方法,用来查找是否有对我们有用的变量和方法呢?
Runtime 中为我们提供了一系列API来获取 Class (类)的 成员变量( Ivar )、属性( Property )、方法( Method )、协议( Protocol ) 等。我们可以通过这些方法来遍历一个类中的成员变量列表、属性列表、方法列表、协议列表。从而查找我们需要的变量和方法。

2. 获取类详细属性、方法

头文件中需引入#import

2.1 获取类的成员变量列表

// 打印成员变量列表
- (void)printIvarList {
    unsigned int count;
    Ivar *ivarList = class_copyIvarList([self class], &count);
    for (unsigned int i = 0; i < count; i++) {
        Ivar myIvar = ivarList[i];
        const char *ivarName = ivar_getName(myIvar);
        NSLog(@"ivar(%d) : %@", i, [NSString stringWithUTF8String:ivarName]);
    }
    free(ivarList);
}

2.2 获取类的属性列表

// 打印属性列表
- (void)printPropertyList {
    unsigned int count;
    
    objc_property_t *propertyList = class_copyPropertyList([self class], &count);
    for (unsigned int i = 0; i < count; i++) {
        const char *propertyName = property_getName(propertyList[i]);
        NSLog(@"propertyName(%d) : %@", i, [NSString stringWithUTF8String:propertyName]);
    }
    
    free(propertyList);
}

2.3 获取类的方法列表

// 打印方法列表
- (void)printMethodList {
    unsigned int count;
    
    Method *methodList = class_copyMethodList([self class], &count);
    for (unsigned int i = 0; i < count; i++) {
        Method method = methodList[i];
        NSLog(@"method(%d) : %@", i, NSStringFromSelector(method_getName(method)));
    }
    
    free(methodList);
}

2.4 获取类所遵循的协议列表

// 打印协议列表
- (void)printProtocolList {
    unsigned int count;
    
    __unsafe_unretained Protocol **protocolList = class_copyProtocolList([self class], &count);
    for (unsigned int i = 0; i < count; i++) {
        Protocol *myProtocal = protocolList[i];
        const char *protocolName = protocol_getName(myProtocal);
        NSLog(@"protocol(%d) : %@", i, [NSString stringWithUTF8String:protocolName]);
    }
    
    free(protocolList);
}

3. 应用场景

3.1 修改私有属性

需求:更改 UITextField 占位文字的颜色和字号
先想想有几种做法:

方法 1:通过 attributedPlaceholder 属性修改

我们知道 UITextField 中有 placeholder 属性和 attributedPlaceholder 属性。通过 placeholder 属性只能更改占位文字,无法修改占位文字的字体和颜色。而通过 attributedPlaceholder 属性我们就可以修改 UITextField 占位文字的颜色和字号了。

方法 2:重写 UITextField 的 drawPlaceholderInRect: 方法修改

实现步骤:

  1. 自定义一个 XXTextField 继承自 UITextField;
  2. 重写自定义 XXTextField 的 drawPlaceholderInRect: 方法;
  3. 在 drawPlaceholderInRect 方法中设置 placeholder 的属性。
- (void)drawPlaceholderInRect:(CGRect)rect {
    
    // 计算占位文字的 Size
    NSDictionary *attributes = @{
                                 NSForegroundColorAttributeName : [UIColor lightGrayColor],
                                 NSFontAttributeName : [UIFont systemFontOfSize:15]
                                 };
    CGSize placeholderSize = [self.placeholder sizeWithAttributes:attributes];
    
    [self.placeholder drawInRect:CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height) withAttributes: attributes];
}

方法 3:利用 Runtime,找到并修改 UITextfield 的私有属性

实现步骤:

  1. 通过获取类的属性列表和成员变量列表的方法打印 UITextfield 所有属性成员变量
  2. 找到私有的成员变量_placeholderLabel
  3. 利用 KVC 对 _placeholderLabel 进行修改。
// 打印 UITextfield 的所有属性和成员变量
- (void)printUITextFieldList {
    unsigned int count;
    
    Ivar *ivarList = class_copyIvarList([UITextField class], &count);
    for (unsigned int i = 0; i < count; i++) {
        Ivar myIvar = ivarList[i];
        const char *ivarName = ivar_getName(myIvar);
        NSLog(@"ivar(%d) : %@", i, [NSString stringWithUTF8String:ivarName]);
    }
    
    free(ivarList);
    
    objc_property_t *propertyList = class_copyPropertyList([UITextField class], &count);
    for (unsigned int i = 0; i < count; i++) {
        const char *propertyName = property_getName(propertyList[i]);
        NSLog(@"propertyName(%d) : %@", i, [NSString stringWithUTF8String:propertyName]);
    }
    
    free(propertyList);
}

// 通过修改 UITextfield 的私有属性更改占位颜色和字体
- (void)createLoginTextField {
    UITextField *loginTextField = [[UITextField alloc] init];
    loginTextField.frame = CGRectMake(15,(self.view.bounds.size.height-52-50)/2, self.view.bounds.size.width-60-18,52);
    loginTextField.delegate = self;
    loginTextField.font = [UIFont systemFontOfSize:14];
    loginTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    loginTextField.textColor = [UIColor blackColor];
    
    loginTextField.placeholder = @"用户名/邮箱";
    [loginTextField setValue:[UIFont systemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    [loginTextField setValue:[UIColor lightGrayColor]forKeyPath:@"_placeholderLabel.textColor"];
    
    [self.view addSubview:loginTextField];
}

3.2 万能控制器跳转

需求:

  1. 某个页面的不同 banner 图,点击可以跳转到不同页面。
  2. 推送通知,点击跳转到指定页面。
  3. 二维码扫描,根据不同内容,跳转不同页面。
  4. WebView 页面,根据 URL 点击不同,跳转不同的原生页面。

先想想有几种做法:

1:在每个需要跳转的地方写一堆判断语句以及跳转语句。
2:将判断语句和跳转语句抽取出来,写到基类,或者对应的 Category 中。
3:利用 Runtime,定制一个万能跳转控制器工具。

实现步骤:

  1. 事先和服务器端商量好,定义跳转不同控制器的规则,让服务器传回对应规则的相关参数。
    比如:跳转到 A 控制器,需要服务器传回 A 控制器的类名,控制器 A 需要传入的属性参数(id、type 等等)。
  2. 根据服务器传回的类名,创建对应的控制器对象;
  3. 遍历服务器传回的参数,利用 Runtime 遍历控制器对象的属性列表;
  4. 如果控制器对象存在该属性,则利用 KVC 进行赋值;
  5. 进行跳转。

首先,定义跳转规则,如下所示。XXViewController 是将要跳转的控制器类名。property 字典中保存的是控制器所需的属性参数。

// 定义的规则
NSDictionary *params = @{
                         @"class" : @"NextViewController",
                         @"property" : @{
                                 @"uid" : @"3",
                                 @"type" : @"NextViewController009"
                                 }
                         };

然后,添加一个工具类 XXJumpControllerTool,添加跳转相关的类方法。

/********************* XXJumpControllerTool.h 文件 *********************/

#import 

@interface XXJumpControllerTool : NSObject

+ (void)pushViewControllerWithParams:(NSDictionary *)params;

@end


/********************* XXJumpControllerTool.m 文件 *********************/

#import "XXJumpControllerTool.h"
#import 
#import 

@implementation XXJumpControllerTool

+ (void)pushViewControllerWithParams:(NSDictionary *)params {
    // 取出控制器类名
    NSString *classNameStr = [NSString stringWithFormat:@"%@", params[@"class"]];
    const char *className = [classNameStr cStringUsingEncoding:NSASCIIStringEncoding];
    
    // 根据字符串返回一个类
    Class newClass = objc_getClass(className);
    if (!newClass) {
        // 创建一个类
        Class superClass = [NSObject class];
        newClass = objc_allocateClassPair(superClass, className, 0);
        // 注册你创建的这个类
        objc_registerClassPair(newClass);
    }

    // 创建对象(就是控制器对象)
    id instance = [[newClass alloc] init];
    
    NSDictionary *propertys = params[@"property"];
    [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        // 检测这个对象是否存在该属性
        if ([XXJumpControllerTool checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
            // 利用 KVC 对控制器对象的属性赋值
            [instance setValue:obj forKey:key];
        }
    }];
    
    
    // 跳转到对应的控制器
    [[XXJumpControllerTool topViewController].navigationController pushViewController:instance animated:YES];
}


// 检测对象是否存在该属性
+ (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName {
    unsigned int count, i;
    
    // 获取对象里的属性列表
    objc_property_t *properties = class_copyPropertyList([instance class], &count);
    
    for (i = 0; i < count; i++) {
        objc_property_t property =properties[i];
        //  属性名转成字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        // 判断该属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return YES;
        }
    }
    free(properties);
    
    return NO;
}

// 获取当前显示在屏幕最顶层的 ViewController
+ (UIViewController *)topViewController {
    UIViewController *resultVC = [XXJumpControllerTool _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [XXJumpControllerTool _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [XXJumpControllerTool _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [XXJumpControllerTool _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

@end

测试代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // 万能跳转控制器
    [self jumpController];
}
-(void)jumpController{
    // 定义的规则
    NSDictionary *params = @{
                             @"class" : @"NextViewController",
                             @"property" : @{
                                     @"ID" : @"123",
                                     @"type" : @"XXViewController1"
                                     }
                             };
    
    [XXJumpControllerTool pushViewControllerWithParams:params];
}

你可能感兴趣的:(iOS 开发:Runtime(详解五)获取类的属性、方法)