前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS中防止数组越界之后发生崩溃

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

作者头像
用户1451823
发布2018-09-13 15:44:13
1.9K0
发布2018-09-13 15:44:13
举报

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337791

在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更新:

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

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年02月20日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档