ios開發(fā)之防數(shù)組越界

ios開發(fā)中,不免會(huì)遇到數(shù)組越界的問題,而當(dāng)數(shù)組越界時(shí)往往會(huì)導(dǎo)致程序的崩潰,結(jié)局的方法之一就是在數(shù)組的分類中使用runtime機(jī)制來交換方法,當(dāng)數(shù)組越界時(shí)返回nil,沒有越界時(shí)返回原本的index.這樣就能達(dá)到防止程序崩潰的問題.

  1. 創(chuàng)建數(shù)組的分類.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSArray (beyond)
@end
  1. 在.m文件中,利用runtime替換數(shù)組中的objectAtIndex:(NSUInteger)index等方法.在方法中判斷是否越界,這樣就可以實(shí)現(xiàn)防止崩潰
#import "NSArray+beyond.h"
@implementation NSArray (beyond)
//每次都會(huì)加載
+(void)load{
    [super load];
     //  替換不可變數(shù)組中的方法
    Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
    Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(__nickyTsui__objectAtIndex:));
    method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
    //  替換可變數(shù)組中的方法
    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(@"數(shù)組越界...");
            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(@"數(shù)組越界...");
            return nil;
        } @finally {
            
        }
    }
    else{
        return [self mutableObjectAtIndex:index];
    }
}
最后編輯于
?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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