API - 類
- 動態(tài)創(chuàng)建一個類(參數(shù):父類,類名,額外的內(nèi)存空間)
- Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)
- 注冊一個類(要在類注冊之前添加成員變量)
- void objc_registerClassPair(Class cls)
#import <objc/runtime.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//創(chuàng)建類
Class newClass = objc_allocateClassPair([NSObject class],"Dog",0);
//第4個參數(shù)表示為對齊褪测,3個為幾個字節(jié)
//添加成員變量
class_addIvar(newClass,"_age",4,1,@encode(int));
class_addIvar(newClass,"_weight",4,1,@encode(int));
class_addMethod(newClass,@selector(run),(IMP)run,"v@:");
//注冊類,一旦類注冊完畢類的結構已經(jīng)決定于未,不能再添加變量
objc_registerClassPair(newClass);
id dog = [[newClass alloc]init];
[dog setValue:@(10) forKey:@"_age"];
[dog setValue:@(20) forKey:@"_weight"];
[dog run];
NSLog(@"age = %@, weight = %@",[dog valueForKey:@"_age"],[dog valueForKey:@"_weight"]);
//在不需要這個類的時候釋放
objc_disposeClassPair(newClass);
return YES;
}
- 銷毀一個類
- void objc_disposeClassPair(Class cls)
- 獲取isa指向的Class
- Class object_getClass(id obj)
- 設置isa指向的Class
- Class object_setClass(id obj, Class cls)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
Person *person = [[Person alloc]init];
[person run];
object_setClass(person,[Car class]);
[person run];
return YES;
}
上面的代碼經(jīng)過 object_setClass
后 person
變?yōu)?Car
類型的忿墅,控制臺的輸出如下:
2022-06-05 16:27:36.180629+0800 TestPod[41697:189747] -[Person run]
2022-06-05 16:30:03.061300+0800 TestPod[41697:189747] -[Car run]
其isa指針變化如下圖所示:
- 判斷一個OC對象是否為Class
- BOOL object_isClass(id obj)
NSLog(@"%d %d %d",object_isClass(person),object_isClass([Person class]), object_isClass(object_getClass([Person class])));
上面除了 person
不是 Class
外,其他兩個都是 Class
- 判斷一個Class是否為元類
- B00L class_isMetaClass(Class cls)
- 獲取父類
- Class class_getSuperclass(Class cls)
API - 成員變量
- 獲取一個實例變量
Ivar class_getInstanceVariable(Class cls, const char *name)
用法如下:
//獲取成員變量信息
Ivar ageVar = class_getInstanceVariable([Person class], "_age");
NSLog(@"%s %s",ivar_getName(ageVar),ivar_getTypeEncoding(ageVar));
輸出結果:
2022-06-07 19:57:59.023243+0800 TestPod[14761:1648955] _age i
- 拷貝實例變量列表(最后需要調用free釋放)
Ivar *class_copyIvarlist(Class cls, unsigned int *outCount)
//成員變量的數(shù)值
unsigned int count;
Ivar *ivars = class_copyIvarList([Person class], &count);
for (int i = 0; i < count; i++)
{
//取出i位置的成員變量
Ivar ivar = ivars[i];
NSLog(@"%s %s",ivar_getName(ivar),ivar_getTypeEncoding(ivar));
}
//runtime中調用copy或者create創(chuàng)建出來的都需要釋放
free(ivars);
輸出結果為:
2022-06-09 10:30:55.223196+0800 TestPod[2000:400561] _age i
2022-06-09 10:30:55.223232+0800 TestPod[2000:400561] _name @"NSString"
通過上面的辦法咬像,我們可以輸出系統(tǒng)類的成員屬性算撮,并通過其他方式來修改它生宛,例如下面這個是通過 KVC
的方式來修改 TextField
的 placeHolder
的文字顏色
//成員變量的數(shù)值
unsigned int count;
Ivar *ivars = class_copyIvarList([UITextField class], &count);
for (int i = 0; i < count; i++)
{
//取出i位置的成員變量
Ivar ivar = ivars[i];
NSLog(@"---%s %s",ivar_getName(ivar),ivar_getTypeEncoding(ivar));
}
//runtime中調用copy或者create創(chuàng)建出來的都需要釋放
free(ivars);
UITextField *textField = [[UITextField alloc]init];
textField.placeholder = @"11111";
//下面這個是拿到打印出來的placeholder相關的一個屬性
UILabel *placeHolderLabel = [textField valueForKey:@"_placeHolderLabel"];
placeHolderLabel.textColor = [UIColor redColor];
//或者用下面的辦法
[textField setValue:[UIColor redColor] forKey:@"_placeHolderLabel.textColor"];
還可以通過給 'NSObject' 添加類別的方式來解析屬性值,如下所示:
#import <objc/runtime.h>>
#import "NSObject+Json.h"
@implementation NSObject (Json)
+ (instancetype)My_objectWithJson:(NSDictionary *)dict
{
id obj = [[self alloc]init];
unsigned int count;
Ivar *ivars = class_copyIvarList(self, &count);
for (int i = 0; i < count; i++)
{
Ivar ivar = ivars[i];
NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
NSMutableString *str = [NSMutableString stringWithString:name];
[str deleteCharactersInRange:NSMakeRange(0, 1)];
//設值
[obj setValue:dict[str] forKey:name];
}
return obj;;
}
然后解析屬性值肮柜,這樣即可:
Person *per = [Person My_objectWithJson:dict];
- 設置和獲取成員變量的值
void object_setIvar(id obj, Ivar ivar, id value)
object_getIvar(id obj, Ivar ivar)
//設置和獲取成員變量的值
Ivar nameIvar = class_getInstanceVariable([Person class],"_name");
Person *p = [[Person alloc]init];
object_setIvar(p, nameIvar, @"123");
object_getIvar(p, nameIvar);
object-setIvar(p, ageIvar, (_bridge id)(void *)10);
NSLog(@"%@",p.name);
//輸出結果
2022-06-07 20:13:33.309974+0800 TestPod[15127:1666081] 123
- 動態(tài)添加成員變量(已經(jīng)注冊的類是不能動態(tài)添加成員變量的)
B00L class_addIvar(Class cls, const char * hane, size_t size, uint8_t alignnent, const char * types) - 獲取成員變量的相關信息
const char *ivar_getName(Ivar v)
const char *ivar_getTypeEncoding(Ivar v)
方法的API
獲得一個實例方法陷舅、類方法
- Method class_getInstanceMethod(Class cls, SEL nane)
- Method class_getClassMethod(Class cls, SEL nane)
方法實現(xiàn)相關操作
- IMP class_getMethodImplementation(Class cls, SEL name)
- IMP method_setImplenentation(Method n, IMP imp)
- void method_exchangeImplenentations(Method ml, Method m2)
#import "Person.h"
@implementation Person
- (void)run
{
NSLog(@"%s",__func__);
}
- (void)test
{
NSLog(@"%s",__func__);
}
@end
#import "Person.h"
#import <objc/runtime.h>>
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [[Person alloc]init];
Method runMethod = class_getInstanceMethod([Person class], @selector(run));
Method testMethod = class_getInstanceMethod([Person class], @selector(test));
method_exchangeImplementations(runMethod, testMethod);
[person run];
}
return 0;
}
拷貝方法列表(最后需要調用free釋放)
- Method *class_copyMethodlist(Class cls, unsigned int woutCount)
·動態(tài)添加方法
- B00L class_addMethod(Class cls,SEL nane,IMP inp,const char *types)
動態(tài)替換方法
- IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
#import "Person.h"
#import <objc/runtime.h>>
#import <Foundation/Foundation.h>
void myRun()
{
NSLog(@"myRun");
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [[Person alloc]init];
class_replaceMethod([Person class], @selector(run), (IMP)myRun, "v");
//或者用下面這種方式
class_replaceMethod([Person class], @selector(run), imp_implementationWithBlock(^{
NSLog(@"123123");
}), "v");
[person run];
}
return 0;
}
獲取方法的相關信息(帶有copy的需要弱用free去釋放)
- SEL method_getName(Method m).
- IMP method_getImplementation(Method m)
- const char *method_getTypeEncoding(Method m)
- unsiqned int method_getNumberOfArguments(Method m)
- char enethod_copyReturnType(Method m)
- char *method_copyArgumentType(Method m, unsigned int index)
Runtime總結
1.什么是Runtime?平時項目中有用過么审洞?
- OC是一門動態(tài)性比較強的編程語言莱睁,允許很多操作推遲到程序運行時再進行
- OC的動態(tài)性就是由Runtime來支撐和實現(xiàn)的,Runtime是一套C語言的API芒澜,封裝了很多動態(tài)性相關的函數(shù)
- 平時編寫的OC代碼仰剿,底層都是轉換成了Runtime APl進行調用
- 具體應用
- 利用關聯(lián)對象(AssociatedObject)給分類添加屬性
- 遍歷類的所有成員變量(修改textfield的占位文字顏色、字典轉模型痴晦、自動歸檔解檔)
- 交換方法實現(xiàn)(交換系統(tǒng)的方法)
- 利用消息轉發(fā)機制解決方法找不到的異常問題
例子
如果想要監(jiān)聽系統(tǒng)的方法南吮,或者在系統(tǒng)方法的基礎上做一些改變,可以使用下面的方法誊酌,這種方式就叫 HOOK
- 例子1
監(jiān)聽按鈕的點擊事件
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSArray *array = [NSArray arrayWithObjects:@"1",nil];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 80, 40);
button.backgroundColor = [UIColor redColor];
[button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)buttonClick
{
NSLog(@"%s",__func__);
}
@end
#import <objc/runtime.h>>
#import "UIControl+Extention.h"
@implementation UIControl (Extention)
+ (void)load
{
Method method1 = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
Method method2 = class_getInstanceMethod(self, @selector(mySendAction:to:forEvent:));
method_exchangeImplementations(method1, method2);
}
- (void)mySendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
NSLog(@"%@---%@---%@",self,target,NSStringFromSelector(action));
if ([self isKindOfClass:[UIButton class]])
{
[self mySendAction:action to:target forEvent:event];
}
}
@end
- 例子2
防止數(shù)組里添加 nil
的對象旨袒,這里注意雖然類型是 NSMutableArray
類型的,但其底層卻不是這樣的术辐,故在交換之前最好通過 [array class]
來打印一下對象的類型
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSObject *obj = nil;
NSMutableArray *array = [NSMutableArray array];
[array addObject:@"1"];
[array insertObject:obj atIndex:0];
}
@end
#import <objc/runtime.h>
#import "NSArray+Extension.h"
@implementation NSArray (Extension)
+ (void)load
{
Class class = NSClassFromString(@"__NSArrayM");
Method method1 = class_getInstanceMethod(class, @selector(insertObject:atIndex:));
Method method2 = class_getInstanceMethod(class, @selector(mj_insertObject:atIndex:));
method_exchangeImplementations(method1, method2);
}
- (void)mj_insertObject:(id)object atIndex:(NSUInteger)index
{
if (object == nil) return;;
[self mj_insertObject:object atIndex:index];
}
@end
通過上面兩個例子我們可以嘗試修改系統(tǒng)字體