背景
最近在做項目的時候用到了運行時,感覺他的代碼很分散,于是寫了一個工具RuntimeTool,把運行時常用的一些操作封裝成了API,歡迎大家使用,如果感覺不錯請記得start。
功能:
- 獲取類所有的變量列表
- 獲取類所有的屬性列表
- 獲取類所有的方法列表
- 通過NSInvocation調用方法
- 運行時動態創建類
- 運行時動態創建方法
- 關聯對象(關聯,獲取,刪除)
- 方法替換
- 設置私有變量
Installation
RuntimeTool支持多種安裝方法
installation with CocoaPods
RuntimeTool is available through CocoaPods. To install
it, simply add the following line to your Podfile:
pod "RuntimeTool",'~>1.0'
然后,運行下面的命令:
pod install
Usage
獲取所有變量列表
[RuntimeTool getVarsForClassName:@"UIView"];
[RuntimeTool getVarsForClass:[UIView class]];
獲取所有的屬性列表
[RuntimeTool getPropertiesForClass:[UIView class]];
[RuntimeTool getPropertiesForClassName:@"UIView"];
獲取所有的方法列表
[RuntimeTool getMethodsForClass:[UIView class]];
[RuntimeTool getMethodsForClassName:@"UIView"];
通過NSInvocation調用方法
TestClass * test = [TestClass new];
id returnValue = [RuntimeTool invokeMethod:test method:@selector(setNum:height:name:) argumentValue:@(10), nil];
運行時動態創建類
Class class = [RuntimeTool createClassOnRuntime:@"MyButton" superClass:@"UIButton"];
運行時動態創建方法
NSString* className = @"MyButton";
NSString* methodStr = @"printLog";
Class newClass = [RuntimeTool createClassOnRuntime:className superClass:@"UIButton"];
[RuntimeTool createMethodForClass:className methodStr:methodStr imp:(IMP)printLog];
id instance = [[newClass alloc]init];
[instance performSelector:NSSelectorFromString(methodStr) withObject:nil];
//方法的實現
void printLog(id self,SEL _cmd) {
printf("hello,world");
}
關聯對象
//給當前controller關聯一個color對象
NSString* key = @"colorKey";
[RuntimeTool createAssociatedObject:self key:key value:[UIColor yellowColor] policy:OBJC_ASSOCIATION_RETAIN];
//獲取color對象并設置背景色
UIColor* color = (UIColor*)[RuntimeTool getAssociatedObjectValue:self key:key];
self.view.backgroundColor = color;
//刪除關聯對象
[RuntimeTool removeAssociatedObjec:self];
[self performSelector:@selector(clearColor) withObject:nil afterDelay:2];
方法替換
- (void)test1 {
NSLog(@"test1");
}
- (void)test2 {
NSLog(@"test2");
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSLog(@"hello,wrold");
}
- (void)swizzle_viewWillAppear:(BOOL)animated{
NSLog(@"world,hello");
}
//方式1(兩個方法相互替換實現):
[self test1];
[RuntimeTool methodExchange:[self class] sel1:@selector(test1) sel2:@selector(test2)];
[self test2];
//輸出結果都是 test1
//方式2(替換某個方法的實現):
[self viewWillAppear:NO];
[RuntimeTool swizzleMethodImp:[self class] sel:@selector(viewWillAppear:) imp:method_getImplementation(class_getInstanceMethod([self class], @selector(swizzle_viewWillAppear:)))];
[self viewWillAppear:NO];
//輸出結果 hello,world world,hello
設置私有變量
TestClass * test = [TestClass new];
test.num = @(100);
NSLog(@"alter before: %@",test.num);
[RuntimeTool setVarForObj:test key:@"_num" value:@(100000)];
NSLog(@"alter after: %@",test.num);
Author
guodongyangw@163.com, guodongyang@qfpay.com
License
RuntimeTool is available under the MIT license. See the LICENSE file for more info.