关于数组安全的思考

项目上线有一段时间了,从崩溃日志统计来看,问题主要还是集中在数组越界,因为项目是2个人写的,我并没有时间看summer写的代码,加上自己在写的时候对网络情况的忽视,导致部分页面会因为数组越界导致崩溃。于是添加一个分类,来解决这个问题刻不容缓。
因为代码过多,项目还是相对较大,所以第一反应就是通过runtime交换方法,增加对数组长度及空元素的判断。
关于runtime的方法交换就不写了,实现内容还是比较简单的,记录一下关于NSMutableArray的增删改查就好了。我们可能在项目中涉及到方法有(如果有没有涉及到的,再自己添加就好了):

//增
- (void)insertObject:(ObjectType)anObject atIndex:(NSUInteger)index;
//删
- (void)removeObjectAtIndex:(NSUInteger)index;
//改(可增)
- (void)setObject:(ObjectType)obj atIndexedSubscript:(NSUInteger)idx NS_AVAILABLE(10_8, 6_0);
//改
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(ObjectType)anObject;
- (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2;
//查
- (ObjectType)objectAtIndex:(NSUInteger)index;

在我们调用上述API的时候,如果没有注意到object是否为空或者index是否越界,程序就会崩溃,而这些元素不单单是有我们控制的,很有可能还和sever有关!

接下来就是方法交换

- (id)mutableObjectIndex:(NSInteger)index{
    if (index >= self.count || index < 0) {
        return nil;
    }
    return [self mutableObjectIndex:index];
}
- (void)mutableInsertObject:(id)object atIndex:(NSUInteger)index
{
    if (object && index <= self.count) {
        [self mutableInsertObject:object atIndex:index];
    }
}
- (void)mutableRemoveObjectAtIndex:(NSUInteger)index
{
    if (index < self.count) {
        [self mutableRemoveObjectAtIndex:index];
    }
}
- (void)mutableExchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2
{
    if (index1 < self.count && index2 < self.count) {
        [self mutableExchangeObjectAtIndex:index1 withObjectAtIndex:index2];
    }
}
- (void)mutableSetObject:(id)object atIndexedSubscript:(NSUInteger)index
{
    if (object && index <= self.count) {
        [self mutableSetObject:object atIndexedSubscript:index];
    }
}
- (void)mutableReplaceObjectAtIndex:(NSUInteger)index withObject:(id)object
{
    if (object && index < self.count) {
        [self mutableReplaceObjectAtIndex:index withObject:object];
    }
}

通过上述方法,基本能够保证到数组的安全了,至少在目前的项目中,是能够起到不错的效果的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型的...
    iOS菜鸟大大阅读 754评论 0 1
  • 1.设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类...
    司马DE晴空阅读 1,331评论 0 7
  • 引导 对于从事 iOS 开发人员来说,所有的人都会答出「 Runtime 是运行时 」,什么情况下用 Runtim...
    Winny_园球阅读 325评论 0 0
  • 今天是幸福感爆棚的日子么?[跳跳][跳跳] 似乎我的幸福银行里满满存下的是↓ Me爱的茶 Me爱的朋友 Me爱的美...
    芊萩阅读 515评论 7 4
  • 人生的价值,并不是用,而是用深度去衡量的。——列夫·托尔斯泰 2017年的区块链行业异常火爆,一个项目紧接着一个,...
    liny52阅读 144评论 0 0