关于分类在开发中我们都经常常见,category在加上runtime能实现好多意想不到的效果,最近在学习中突然了解到category可以省下好多代码。这对于是小白的我感觉 像打开了新天地。
最近在阅读博客的时候,发现一篇文章,如何判断数组越界的情况,如果一行一行的判断写,不近费事费时,还不一定所有的都能判断到,但是如果在编译的时候就替换系统的方法,这样我们就不用逐个判断了。
在说分类之前需要先了解一些load 和 initialize的区别
load:是在main函数调用之前就已经加载的方法
initialize:是在main函数之后init方法之前加载的方法,主要进行一些初始化的操作
此外还想在多说两句,load加载类的时候,加载的顺序是类,子类,分类,注意如果有好多分类的时候,加载的顺序是根据编译的书序来判断的。有兴趣的朋友可以详细看一下分类。
而调用的时候顺序正好相反,分类,子类,类。分类如果实现了父类的方法,则会覆盖掉父类的方法。而load方法不会覆盖。
下面进入正题,话不多说直接上代码
+ (void)load{
//替换objectAtIndex方法
MethodfromMethod =class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(objectAtIndex:));
MethodtoMethod =class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(wb_objectAtIndex:));
method_exchangeImplementations(fromMethod, toMethod);
//替换array【0】获取元素的方法
MethodfromMethod1 =class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(objectAtIndexedSubscript:));
MethodtoMethod1 =class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(wb_objectAtIndexedSubscript:));
method_exchangeImplementations(fromMethod1, toMethod1);
//替换objectAtIndex方法
MethodmfromMethod =class_getInstanceMethod(objc_getClass("__NSArrayM"),@selector(objectAtIndex:));
MethodmtoMethod =class_getInstanceMethod(objc_getClass("__NSArrayM"),@selector(wb_mobjectAtIndex:));
method_exchangeImplementations(mfromMethod, mtoMethod);
//替换array【0】获取元素的方法
MethodmfromMethod1 =class_getInstanceMethod(objc_getClass("__NSArrayM"),@selector(objectAtIndexedSubscript:));
MethodmtoMethod1 =class_getInstanceMethod(objc_getClass("__NSArrayM"),@selector(wb_mobjectAtIndexedSubscript:));
method_exchangeImplementations(mfromMethod1, mtoMethod1);
}
-(id)wb_objectAtIndexedSubscript:(NSUInteger)index{
if(self.count-1< index|| !self.count) {
@try{
return [self wb_objectAtIndexedSubscript:index];
}@catch(NSException *exception) {
// 在崩溃后会打印崩溃信息。如果是线上,可以在这里将崩溃信息发送到服务器
NSLog(@"---------- %s Crash Because Method %s ----------\n", class_getName(self.class), __func__);
NSLog(@"%@",[exceptioncallStackSymbols]);
returnnil;
}@finally{
}
}else{
return [self wb_objectAtIndexedSubscript:index];
}
}
-(id)wb_objectAtIndex:(NSUInteger)index{
if(self.count-1< index|| !self.count) {
@try{
return[selfwb_objectAtIndex:index];
}@catch(NSException *exception) {
// 在崩溃后会打印崩溃信息。如果是线上,可以在这里将崩溃信息发送到服务器
NSLog(@"---------- %s Crash Because Method %s ----------\n", class_getName(self.class), __func__);
NSLog(@"%@",[exceptioncallStackSymbols]);
returnnil;
}@finally{
}
}else{
return[selfwb_objectAtIndex:index];
}
}
-(id)wb_mobjectAtIndexedSubscript:(NSUInteger)index{
if(self.count-1< index) {
@try{
return [self wb_mobjectAtIndexedSubscript:index];
}@catch(NSException *exception) {
// 在崩溃后会打印崩溃信息。如果是线上,可以在这里将崩溃信息发送到服务器
NSLog(@"---------- %s Crash Because Method %s ----------\n", class_getName(self.class), __func__);
NSLog(@"%@",[exceptioncallStackSymbols]);
returnnil;
}@finally{
}
}else{
return [self wb_mobjectAtIndexedSubscript:index];
}
想深入了解的可以看一下这偏如果让分类不覆盖类方法:https://www.jianshu.com/p/81291aceceb2
网友评论