美文网首页
ios开发之防数组越界

ios开发之防数组越界

作者: 飞扬的青春8780975 | 来源:发表于2017-02-25 15:10 被阅读0次

ios开发中,不免会遇到数组越界的问题,而当数组越界时往往会导致程序的崩溃,结局的方法之一就是在数组的分类中使用runtime机制来交换方法,当数组越界时返回nil,没有越界时返回原本的index.这样就能达到防止程序崩溃的问题.

  1. 创建数组的分类.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSArray (beyond)
@end
  1. 在.m文件中,利用runtime替换数组中的objectAtIndex:(NSUInteger)index等方法.在方法中判断是否越界,这样就可以实现防止崩溃
#import "NSArray+beyond.h"
@implementation NSArray (beyond)
//每次都会加载
+(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);
    //  替换可变数组中的方法
    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(@"数组越界...");
            return nil;
        } @finally {
            
        }
    }
    else{
        return [self __nickyTsui__objectAtIndex:index];
    }
}
-(id)mutableObjectAtIndex:(NSUInteger)index{
    if (index > self.count - 1 || !self.count){
        @try {
            return [self mutableObjectAtIndex:index];
        } @catch (NSException *exception) {
            //__throwOutException  抛出异常
            NSLog(@"数组越界...");
            return nil;
        } @finally {
            
        }
    }
    else{
        return [self mutableObjectAtIndex:index];
    }
}

相关文章

  • ios开发之防数组越界

    ios开发中,不免会遇到数组越界的问题,而当数组越界时往往会导致程序的崩溃,结局的方法之一就是在数组的分类中使用r...

  • iOS 数组越界的处理和优化方案。

    iOS开发中最常见的列表数据,必须使用数组,但是使用数组总会出现数组越界的情况,下面列出三种优化数组越界的方式。 ...

  • iOS--再也不用担心数组越界

    iOS--再也不用担心数组越界 iOS--再也不用担心数组越界

  • iOS array数组防越界

    iOS开发中常用到array数组,本文介绍一个防止数组越界的方法,分享给有需要的人;首先创建NSArray的Cat...

  • iOS数组越界的保护

    先上一段代码 在iOS中, 上述两种取数组元素的方法都会导致程序崩溃, 称为"数组越界", 那么在日常开发中,因为...

  • iOS 数组 NSArray 遍历 懒加载总结

    iOS开发之懒加载 iOS中数组遍历的方法及比较

  • swift扩展类-Array

    在使用数组的时候,最常见的异常就是数组越界了,为了避免在开发的时候出现越界的情况,写了几个扩展的方法,用于缓减越界...

  • 03Runtime

    应用场景:1.处理数组越界, 防崩溃库method_exchangeImplementationsclass_ge...

  • iOS开发之数组越界(Terminating app due t

    对于刚刚接触数组的新同学来说,应该最多遇到的就是类似于下面这样的报错了吧: 类似的还有: 以上都是数组越界相关的问...

  • iOS-Runtime之数组越界

    关于数组越界目前大概有两种方式,一种是通过分类添加安全的索引方法,第二种就是Runtime实现,第一种如果是个人开...

网友评论

      本文标题:ios开发之防数组越界

      本文链接:https://www.haomeiwen.com/subject/dtxnwttx.html