iOS中防止数组越界之后发生崩溃

在iOS开发中有时会遇到数组越界的问题,从而导致程序崩溃。为了防止程序崩溃,我们就要对数组越界进行处理。通过上网查资料,发现可以通过为数组写一个分类来解决此问题。

基本思路:为NSArray写一个防止数组越界的分类。分类中利用runtime将系统中NSArray的对象方法objectAtIndex:替换,然后对objectAtIndex:传递过来的下标进行判断,如果发生数组越界就返回nil,如果没有发生越界,就继续调用系统的objectAtIndex:方法

代码:

.h文件:

#import <Foundation/Foundation.h>

#import <objc/runtime.h>

@interface NSArray (beyond)


@end


.m文件:

#import "NSArray+beyond.h"


@implementation NSArray (beyond)

+ (void)load{

    [superload];

     //  替换不可变数组中的方法

    Method oldObjectAtIndex =class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(objectAtIndex:));

    Method newObjectAtIndex =class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(__nickyTsui__objectAtIndex:));

    method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);

    //  替换可变数组中的方法

    Method oldMutableObjectAtIndex =class_getInstanceMethod(objc_getClass("__NSArrayM"),@selector(objectAtIndex:));

    Method newMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"),@selector(mutableObjectAtIndex:));

    method_exchangeImplementations(oldMutableObjectAtIndex, newMutableObjectAtIndex);

}


- (id)__nickyTsui__objectAtIndex:(NSUInteger)index{

    if (index >self.count -1 || !self.count){

        @try {

            return [self__nickyTsui__objectAtIndex:index];

        } @catch (NSException *exception) {

            //__throwOutException  抛出异常

            NSLog(@"数组越界...");

            returnnil;

        } @finally {

            

        }

    }

    else{

        return [self__nickyTsui__objectAtIndex:index];

    }

}


- (id)mutableObjectAtIndex:(NSUInteger)index{

    if (index >self.count -1 || !self.count){

        @try {

            return [selfmutableObjectAtIndex:index];

        } @catch (NSException *exception) {

            //__throwOutException  抛出异常

            NSLog(@"数组越界...");

            returnnil;

        } @finally {

            

        }

    }

    else{

        return [selfmutableObjectAtIndex:index];

    }

}

@




2018.06.01更新:

这里有一个防止数组越界崩溃的升级版,即使arr[index]这种情况下产生的崩溃也能防止。

传送门:https://www.jianshu.com/writer#/notebooks/2349590/notes/28096621


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值