1. 數(shù)組越界 訪問為空是我們的app的一大元兇,當(dāng)訪問數(shù)組經(jīng)常會(huì)訪問為空,這是就會(huì)拋出異常導(dǎo)致app閃退,有時(shí)當(dāng)我們測試時(shí)數(shù)據(jù)是好的,但是在上線以后有可能后臺(tái)修改數(shù)據(jù)有問題,導(dǎo)致前段訪問數(shù)據(jù)時(shí)造成訪問數(shù)組訪問為空越界,
2. 可變數(shù)組添加元素是,元素不能為空,當(dāng)為空時(shí)將發(fā)出異常,導(dǎo)致app崩潰閃退
下面我將介紹使用runtime替換系統(tǒng)的方法防止數(shù)組增刪改查出現(xiàn)問題直接崩潰
首先創(chuàng)建一個(gè)類目 繼承自NSMutableArray
@interface NSMutableArray (categary)
導(dǎo)入#import <objc/runtime.h>
使用系統(tǒng)的類方法+load{}
這里先介紹load方法
+load方法是一個(gè)類方法,應(yīng)用啟動(dòng)的時(shí)候加載所有的類,這時(shí)就會(huì)調(diào)用類方法
load方法被添加到runtime時(shí)開始執(zhí)行 父類首先執(zhí)行,之后是子類最后才到categary 又因?yàn)槭侵苯荧@取函數(shù)指針來執(zhí)行,不會(huì)像 objc_msgSend 一樣會(huì)有方法查找的過程
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method newMethod = class_getClassMethod([self class], @selector(cq_objectAtIndex:));
Method method = class_getClassMethod([self class], @selector(objectAtIndex:));
//交換系統(tǒng)的取數(shù)組元素的方法
method_exchangeImplementations(newMethod, method);
Method addNewMethod = class_getClassMethod([self class], @selector(cq_addObject:));
Method addmethod = class_getClassMethod([self class], @selector(addObject:));
//交換系統(tǒng)添加元素到數(shù)組的方法
method_exchangeImplementations(addNewMethod, addmethod);
Method removeNewMethod = class_getClassMethod([self class], @selector(cq_safeRemoveObject:));
Method removemethod = class_getClassMethod([self class], @selector(removeObject:));
//交換系統(tǒng)移除數(shù)組元素的方法
method_exchangeImplementations(removeNewMethod, removemethod);
});
}
這里使用GCD的單例表示是只創(chuàng)建一次,因?yàn)槊看晤愓{(diào)用的時(shí)候都會(huì)加載load類方法
//取值
- (id)cq_objectAtIndex:(NSUInteger)index
{
if (self.count == 0) {
NSLog(@"%s mutArray None Object",__func__);
return nil;
}
if (index > self.count) {
NSLog(@"%s index out of mutArrayCount",__func__);
return nil;
}
return [self cq_objectAtIndex:index];
}
//向數(shù)組添加元素
- (void)cq_addObject:(id)object
{`
if (object == nil) {
NSLog(@"%s can add nil object into NSMutableArray", __FUNCTION__);
} else {
[self cq_addObject:object];
}
}
//移除指定下標(biāo)元素
- (void)cq_RemoveObjectAtIndex:(NSUInteger)index {
if (self.count <= 0) {
NSLog(@"%s can't get any object from an empty array", __FUNCTION__);
return;
}
if (index >= self.count) {
NSLog(@"%s index out of bound", __FUNCTION__);
return;
}
[self cq_RemoveObjectAtIndex:index];
}
//插入元素到指定下標(biāo)位置
- (void)cq_insertObject:(id)anObject atIndex:(NSUInteger)index {
if (anObject == nil) {
NSLog(@"%s can't insert nil into NSMutableArray", __FUNCTION__);
} else if (index > self.count) {
NSLog(@"%s index is invalid", __FUNCTION__);
} else {
[self cq_insertObject:anObject atIndex:index];
}
}
//移除特定元素
- (void)cq_safeRemoveObject:(id)obj {
if (obj == nil) {
NSLog(@"%s call -removeObject:, but argument obj is nil", __FUNCTION__);
return;
}
[self cq_safeRemoveObject:obj];
}