iOS动态添加属性

如何在不破坏原有类封装下添加属性( 动态添加property )

当我们想给系统类或者自定义基类添加某个属性(简称propertyName)时,在不破坏原有类封装情形下,可以使用继承(直接添加属性)和分类(动态添加属性)。

注: 推荐使用分类Object-C,因为使用继承,所有使用到propertyName都需要继承自定义属性类,侵入性太强。

动态添加属性原理

利用runtime的特性,在第一次加载时添加属性

Object-C为分类添加属性

主要用到的runtime方法`:

  • class_addProperty:添加属性
  • class_addMethod:添加方法
  • class_replaceProperty:替换属性
  • class_getInstanceVariable:获取成员变量ivar

下面就简单介绍下关键步骤,详细会附上代码链接:

1.判断是否存在该成员变量,如果存在则无需进行后续操作,不存在就动态添加:

   /**
    targetClass:  表示要添加的属性的类
    propertyName: 表示要添加的属性名
   */
   Ivar ivar = class_getInstanceVariable(targetClass, [[NSString stringWithFormat:@"_%@", propertyName] UTF8String]);

2.添加属性(class_addProperty调用后会返回一个BOOL值。成功(返回YES)则添加属性,失败(返回NO)则动态替换属性):

    // value:属性的赋值,根据属性值,判断属性类型
    objc_property_attribute_t type = { "T", [[NSString stringWithFormat:@"@\"%@\"",NSStringFromClass([value class])] UTF8String] };
    objc_property_attribute_t ownership = { "&", "N" };
    objc_property_attribute_t backingivar  = { "V", [[NSString stringWithFormat:@"_%@", propertyName] UTF8String] };
    objc_property_attribute_t attrs[] = { type, ownership, backingivar };
   /**
    targetClass:   表示要添加的属性的类
    propertyName:  表示要添加的属性名
    attrs:        类特性列表
    attrsCount:    类特性个数
   */
   unsigned int attrsCount = 3;
   class_addProperty(targetClass, [propertyName UTF8String], attrs, attrsCount)

注:类特性,可以通过property_getAttributes去获取查看,class_copyPropertyList获取属性列表。符号表:
Type Encodings

3.动态替换属性(属性添加失败执行):

class_replaceProperty(targetClass, [propertyName UTF8String], attrs, attrsCount);

4.动态添加set和get方法(不管添加属性成功失败与否都要添加):

- (void)addMethod(Class _Nullable targetClass, NSString * propertyName)
{
    // 动态添加方法就不详细去描述了,本文会附上一篇对runtime介绍比较详细的博客链接可以去看一下(关键点在于SEL和IMP,和OC运行会被汇编转换成C代码去执行)
    // 链接搜索关键字:Objective-C Runtime
    class_addMethod(targetClass, NSSelectorFromString(propertyName), (IMP)customGetter, "@@:");
    class_addMethod(targetClass, NSSelectorFromString([NSString stringWithFormat:@"set%@:",[propertyName capitalizedString]]), (IMP)customSetter, "v@:@");
}


// 这里我是用一个字典作为容器,以属性名为key去存储新属性值.
id customGetter(id targetClass, SEL _targetCmd) {
    if (dictCustomerProperty == nil) {
        dictCustomerProperty = [NSMutableDictionary new];
    }
    NSString *key = NSStringFromSelector(_targetCmd);
    return [dictCustomerProperty objectForKey:key];
}

void customSetter(id targetClass, SEL _targetCmd, id newValue) {
    //移除set
    NSString *key = [NSStringFromSelector(_targetCmd) stringByReplacingCharactersInRange:NSMakeRange(0, 3) withString:@""];
    //首字母小写
    NSString *head = [key substringWithRange:NSMakeRange(0, 1)];
    head = [head lowercaseString];
    key = [key stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:head];
    //移除后缀 ":"
    key = [key stringByReplacingCharactersInRange:NSMakeRange(key.length - 1, 1) withString:@""];
    
    if (dictCustomerProperty == nil) {
        dictCustomerProperty = [NSMutableDictionary new];
    }
    
    [dictCustomerProperty setObject:newValue forKey:key];
}

关键点也就这些地方了,这种方法的优点在于,生成的属性是动态添加进类中的。可以使用class_copyPropertyList获取到的。

注:runtime API介绍博客

Objective-C Runtime

封装

实现过于繁琐,所有进行简单封装,使用方式在所需拓展分类中,添加声明和方法注册即可,无需实现set和get。
封装实现:RMProperty

.h文件

#import 

@interface NSString (RMProperty)
@property (nonatomic, strong) NSString    *test;
@property (nonatomic, strong) NSDictionary *dict;
@end

.m文件

#import "NSString+RMProperty.h"
#import "RMProperty.h"
@implementation NSString (RMProperty)
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [RMProperty addPropertyWithtarget:[self new] withPropertyName:@"test" withValue:[NSString new]];
        [RMProperty addPropertyWithtarget:[self new] withPropertyName:@"dict" withValue:[NSDictionary new]];
    });
}
@end
```·

你可能感兴趣的:(iOS动态添加属性)