学习计划(8) -runtime - iOS 中防止数组越界的办法

项目中经常遇到数组越界的情况,这是个很烦人的问题,所以,就思考了下如何避免这样的问题。
首先我们获取数组元素的方式分为:

NSArray *array = @[@1,@2];
NSLog(@"arrary: %@",[array objectAtIndex:2]);
NSLog(@"arrary: %@",array[2]);

是的,通过objectAtIndex和[] 方式。

然后我们是不是第一个想法就是写分类然后重写?
嗯,我的确是试了一下,然后发现并没有用,系统这样提示我:

Category is implementing a method which will also be implemented by its primary class

WTF? 警告,说这里重写也没有用?那怎么办?
而且还有一个问题就是,objectAtIndex方法很明确了,那么[] 这是个什么鬼?这也能用方法来表示?是的。
有两种方式可以知道:
第一种直接看错误:

2017-12-29 19:25:36.510723+0800 OCTest[39152:4167702] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndexedSubscript:]: index 3 beyond bounds [0 .. 1]'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff4150700b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fff680e5c76 objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff41548514 _CFThrowFormattedException + 202
    3   CoreFoundation                      0x00007fff415b9201 -[__NSArrayI objectAtIndexedSubscript:] + 97
    4   OCTest                              0x0000000100000e55 main + 245
    5   libdyld.dylib                       0x00007fff68cd5115 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

我们人为越界了一下,发现了错误所在
[__NSArrayI objectAtIndexedSubscript:]
是的,这里告诉我们就是它发生了错误.
第二种:

在main.m文件中写下如下代码:
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSArray *array = @[@1,@2];
        NSLog(@"arrary: %@",[array objectAtIndex:2]);
        NSLog(@"arrary: %@",array[3]);
    }
    return 0;
}

然后通过命令行:
clang -rewrite-objc main.m
得到
main.cpp
拉倒最后:
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        NSArray *array = ((NSArray *(*)(Class, SEL, ObjectType  _Nonnull const * _Nonnull, NSUInteger))(void *)objc_msgSend)(objc_getClass("NSArray"), sel_registerName("arrayWithObjects:count:"), (const id *)__NSContainer_literal(2U, ((NSNumber *(*)(Class, SEL, int))(void *)objc_msgSend)(objc_getClass("NSNumber"), sel_registerName("numberWithInt:"), 1), ((NSNumber *(*)(Class, SEL, int))(void *)objc_msgSend)(objc_getClass("NSNumber"), sel_registerName("numberWithInt:"), 2)).arr, 2U);
        NSLog((NSString *)&__NSConstantStringImpl__var_folders_2d_q947d5pn4z3dfyq0j4vqsq840000gn_T_main_9976d7_mi_0,((id (*)(id, SEL, NSUInteger))(void *)objc_msgSend)((id)array, sel_registerName("objectAtIndexedSubscript:"), (NSUInteger)1));
        NSLog((NSString *)&__NSConstantStringImpl__var_folders_2d_q947d5pn4z3dfyq0j4vqsq840000gn_T_main_9976d7_mi_1,((id (*)(id, SEL, NSUInteger))(void *)objc_msgSend)((id)array, sel_registerName("objectAtIndex:"), (NSUInteger)1));
    }
    return 0;
}

通过代码我们也知道了[]调用的方式:
sel_registerName("objectAtIndexedSubscript:")
里面的objectAtIndexedSubscript方法就是当我们使用[]的时候底层调用的方法。
当然,它也无法重写。

知道了原因,我们却无法重写,真是一个悲伤的故事。于是我找啊找啊,就找到了一种可以替代方法的方法。不给上,哥就不上了? 那也太怂了是吧。
我找到的就是runtime中的替换方法。
官方解释网址:

https://developer.apple.com/documentation/objectivec/1418530-class_getinstancemethod

Method class_getInstanceMethod(Class cls, SEL name);
Returns a specified instance method for a given class.
为给定的类返回指定的实例方法。

我们先通过这个方法获取指定的实例方法.

https://developer.apple.com/documentation/objectivec/1418769-method_exchangeimplementations

void method_exchangeImplementations(Method m1, Method m2);
Exchanges the implementations of two methods.
交换两种方法的实现。

然后我们再自己实现个方法,这方法里面我们做一下规避操作。比如用try catch把异常给捕捉起来,然后打上日志。就不用担心会崩溃,也不知道哪里发生了错误。当然具体的方法要根据业务场景自我实现。

下面的__NSArrayI 和__NSArrrayM分别代表不可变数组和可变数组的真实类型

NSLog(@"type of array:%@",[array class]);
NSLog(@"type of mutableArray:%@",[mArray class]);

结果如下:
2017-12-29 19:46:08.048887+0800 OCTest[39319:4202006] type of array:__NSArrayI
2017-12-29 19:46:08.048905+0800 OCTest[39319:4202006] type of mutableArray:__NSArrayM

代码如下:

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

@implementation NSArray (BoundsOfRang)

+ (void)load{
    [super load];
    // 替换不可变数组中的方法 objectAtIndex
    Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
    Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(newObjectAtIndex:));
    method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
    // 替换不可变数组中的方法 []调用的方法
    Method oldMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndexedSubscript:));
    Method newMutableObjectAtIndex =  class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(newObjectAtIndexedSubscript:));
    method_exchangeImplementations(oldMutableObjectAtIndex, newMutableObjectAtIndex);
    
    // 替换可变数组中的方法 objectAtIndex
    Method oldMObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:));
    Method newMObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(newMutableObjectAtIndex:));
    method_exchangeImplementations(oldMObjectAtIndex, newMObjectAtIndex);
    // 替换可变数组中的方法  []调用的方法
    Method oldMMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndexedSubscript:));
    Method newMMutableObjectAtIndex =  class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(newMutableObjectAtIndexedSubscript:));
    method_exchangeImplementations(oldMMutableObjectAtIndex, newMMutableObjectAtIndex);
}

- (id)newObjectAtIndex:(NSUInteger)index{
    if (index > self.count - 1 || !self.count){
        @try {
            return [self newObjectAtIndex:index];
        } @catch (NSException *exception) {
            NSLog(@"不可数组越界了");
            return nil;
        } @finally {

        }
    }
    else{
        return [self newObjectAtIndex:index];
    }
}

- (id)newObjectAtIndexedSubscript:(NSUInteger)index{
    if (index > self.count - 1 || !self.count){
        @try {
            return [self newObjectAtIndexedSubscript:index];
        } @catch (NSException *exception) {
            NSLog(@"不可数组越界了");
            return nil;
        } @finally {
        }
    }
    else{
        return [self newObjectAtIndexedSubscript:index];
    }
}



- (id)newMutableObjectAtIndex:(NSUInteger)index{
    if (index > self.count - 1 || !self.count){
        @try {
            return [self newMutableObjectAtIndex:index];
        } @catch (NSException *exception) {
            NSLog(@"可变数组越界了");
            return nil;
        } @finally {
            
        }
    }
    else{
        return [self newMutableObjectAtIndex:index];
    }
}

- (id)newMutableObjectAtIndexedSubscript:(NSUInteger)index{
    if (index > self.count - 1 || !self.count){
        @try {
            return [self newMutableObjectAtIndexedSubscript:index];
        } @catch (NSException *exception) {
            NSLog(@"可变数组越界了");
            return nil;
        } @finally {
        }
    }
    else{
        return [self newMutableObjectAtIndexedSubscript:index];
    }
}
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容