博客> iOSruntime创建对象
iOSruntime创建对象
2019-12-09 04:20 评论:0 阅读:5016 我的逆向倾斜
ios oc JS交互

@implementation UIView (racCerate)

  • (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Class class = [self class];

    SEL originalSelector = @selector(initWithFrame:);
    SEL swizzledSelector = @selector(wl_initWithFrame:);
    
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (success) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }

    }); }

  • (instancetype)wl_initWithFrame:(CGRect)frame { UIView *view = [self wl_initWithFrame:frame];

    NSBundle *mainB = [NSBundle bundleForClass:[view class]];

    //自定义的类 if (mainB == [NSBundle mainBundle]) {

    NSArray *dicKeyArray = [self getAllProperties];
    
    for (int i = 0; i < dicKeyArray.count; i ++) {
    
        NSString *setName = dicKeyArray[i];
    
        NSRange range = [setName rangeOfString:@"wl_rac"]; //这里写了个判断 防止其他对象创建
    
        if (range.location != NSNotFound) {
    
            SEL setSel = [self creatSetterWithPropertyName:setName];
    
            if ([self respondsToSelector:setSel]) {
    
                [self performSelectorOnMainThread:setSel
                                       withObject:[RACSubject subject]
                                    waitUntilDone:[NSThread isMainThread]];
            }                
        }
    }

    }

    return view; }

pragma mark - 获取self中所有属性

  • (NSArray )getAllProperties { u_int count; objc_property_t properties =class_copyPropertyList([self class], &count); NSMutableArray propertiesArray = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i<count; i++){ const char propertyName =property_getName(properties[i]); [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]]; } free(properties); return propertiesArray; }

pragma mark - 数据整理

  • (SEL)creatSetterWithPropertyName:(NSString *)propertyName { propertyName = [NSString stringWithFormat:@"set%@%@:",[[propertyName substringToIndex:1] uppercaseString],[propertyName substringFromIndex:1]];

    //3.返回set方法 return NSSelectorFromString(propertyName); } @end

/ ----------------------- 图 ------------------------ - /  屏幕快照 2018-08-21 上午9.54.25.png

 屏幕快照 2018-08-21 上午9.54.32.png

/----------------------- 使用方法-------------------------/  屏幕快照 2018-08-21 上午9.47.38.png

 屏幕快照 2018-08-21 上午9.47.52.png

收藏
0
sina weixin mail 回到顶部