iOS开发 - runtime运行时一些实用方法

1、从别的类拷贝方法

//说明:StyleKit是类名 该方法寻找类中包含draw的方法

- (void)searchMethods

{

    self.methodsArray = [@[] mutableCopy];

    int unsigned numMethods;

    Method *methods = class_copyMethodList(objc_getMetaClass("StyleKit"), &numMethods);

    for (int i = 0; i < numMethods; i++) {

        NSString *stringFromSelector = NSStringFromSelector(method_getName(methods[i]));

        if ([stringFromSelector rangeOfString:@"draw"].location != NSNotFound) {

            [self.methodsArray addObject:stringFromSelector];

        }

    }

    free(methods);

}


//说明:self.imageList 整数取0即可 将StyleKit类中搜出来的方法,通过IMP调用执行

- (void)drawRect:(CGRect)rect

{

    if (self.imageList < self.methodsArray.count) {

        SEL paintCodeSelector = NSSelectorFromString(self.methodsArray[self.imageList]);

        [StyleKit setDesiredFillColor:self.fillColor];

        IMP imp = [[StyleKit class] methodForSelector:paintCodeSelector];

        void (*func)(id, SEL) = (void *)imp;

        func([StyleKit class], paintCodeSelector);

    }

}


你可能感兴趣的:(iOS开发 - runtime运行时一些实用方法)