iOS數(shù)組越界的保護(hù)

先上一段代碼

    NSArray *testArray = @[@"a",@"b",@"c"];
    NSLog(@"%@",[testArray objectAtIndex:3]);
    NSLog(@"%@",testArray[3]);

在iOS中, 上述兩種取數(shù)組元素的方法都會(huì)導(dǎo)致程序崩潰, 稱為"數(shù)組越界", 那么在日常開發(fā)中,因?yàn)閿?shù)據(jù)的不確定性, 如果每次取指定index的元素前都要對(duì)數(shù)組的count進(jìn)行判斷,會(huì)非常繁瑣, 也會(huì)增加代碼量.

這里介紹一種簡(jiǎn)單的全局方法, 是通過tuntime的method swizzling實(shí)現(xiàn)的:

為NSArray添加一個(gè)category

#import <Foundation/Foundation.h>

///對(duì)數(shù)組越界進(jìn)行保護(hù)
// 適用于 objectAtIndex 的保護(hù) ,對(duì) array[index] 無效
// runtime實(shí)現(xiàn), 無需導(dǎo)入頭文件

@interface NSArray (DHArraySafe)

@end



#import "NSArray+ DHArraySafe.h"
#import <objc/runtime.h>

@implementation NSArray (DHArraySafe)

+ (void)load{
    [super load];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{  //方法交換只要一次就好
        Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
        Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(__nickyTsui__objectAtIndex:));
        method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
    });
}
- (id)__nickyTsui__objectAtIndex:(NSUInteger)index{
    if (index > self.count - 1 || !self.count){
        @try {
            return [self __nickyTsui__objectAtIndex:index];
        } @catch (NSException *exception) {
            //__throwOutException  拋出異常
            return nil;
        } @finally {
            
        }
    }
    else{
        return [self __nickyTsui__objectAtIndex:index];
    }
}
@end

//mutableArray的對(duì)象也需要做方法交換
@interface NSMutableArray (DHArraySafe)

@end
@implementation NSMutableArray (DHArraySafe)

+ (void)load{
    [super load];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{  //方法交換只要一次就好
        Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:));
        Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(__nickyTsui__objectAtIndex:));
        method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
    });
}
- (id)__nickyTsui__objectAtIndex:(NSUInteger)index{
    if (index > self.count - 1 || !self.count){
        @try {
            return [self __nickyTsui__objectAtIndex:index];
        } @catch (NSException *exception) {
            //__throwOutException  拋出異常
            return nil;
        } @finally {
            
        }
    }
    else{
        return [self __nickyTsui__objectAtIndex:index];
    }
}
@end

注意:

1.對(duì)數(shù)組越界進(jìn)行保護(hù)
2.適用于 objectAtIndex 的保護(hù) ,對(duì) array[index] 無效
3.runtime實(shí)現(xiàn), 無需導(dǎo)入頭文件, 一次添加,對(duì)全局工程有效

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容