您的位置:首页 > 移动开发 > IOS开发

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

2017-02-20 11:48 471 查看
在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];

    }

}

@
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: