您的位置:首页 > 移动开发 > Objective-C

Objective-c防止数组越界而崩溃(全局效果)

2017-02-14 17:17 375 查看
数组越界其实是很基本的问题,但是解决起来除了count的判断,还有每个调用的时候都要去判断一遍

对于不明确的数据总会有崩溃的风险

然而 每次调用都判断 那是太累了

so 。。runtime&category提供了一个比较简洁的解决方案

首先把NSArray/NSMutableArray的objectAtIndex方法通过objc的runtime 里面method swizzle把方法进行替换

+ (void)load{
[super load];
Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(__nickyTsui__objectAtIndex:));
method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
}


可以看到 旧方法跟新方法的名字(在上面两个selector里面)

接着写上新方法即可

在新方法里面做越界判断

- (id)__nickyTsui__objectAtIndex:(NSUInteger)index{
if (index > self.count - 1 || !self.count){
@try {
return [self __nickyTsui__objectAtIndex:index];
} @catch (NSException *exception) {
//__throwOutException  抛出异常
return nil;
} @finally {

}
}
else{
return [self __nickyTsui__objectAtIndex:index];
}
}


把这个NSArray的category加到pch就好了。。

转载自:http://www.cnblogs.com/n1ckyxu/p/6047556.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: