IOS 中runtime 不可變數組__NSArray0 和__NSArrayI

來源:互聯網
上載者:User

標籤:越界   不同的   int   不能   ati   指標   self   time   rom   

IOS 中runtime 不可變數組__NSArray0 和__NSArrayI

 

大家可能都遇到過項目中不可變數組避免數組越界的處理:runtime,然而有時候並不能解決所有的問題,因為類簇不一樣

#import "NSArray+Security.h"

#import "NSObject+Swizzling.h"

 

@implementation NSArray (Security)

 

+ (void)load {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        [objc_getClass("__NSArray0") methodSwizzlingWithOriginalSelector:@selector(objectAtIndex:) bySwizzledSelector:@selector(safeObjectAtIndex:)];

    });

}

 

 

- (id)safeObjectAtIndex:(NSUInteger)index {

    if (self.count == 0) {

        NSLog(@"%s can‘t get any object from an empty array", __FUNCTION__);

        return nil;

    }

    if (index > self.count) {

        NSLog(@"%s index out of bounds in array", __FUNCTION__);

        return nil;

    }

    return [self safeObjectAtIndex:index];

}

 

@end

 

但是不同的建立數組的方法導致不同的類簇(其實也就是不同的指標),下面我們就看

NSArray *arr1 =  @[@"1",@"2"];

NSArray *arr2 =  [[NSArray alloc]init];

NSArray *arr2 =  [[NSArray alloc]initwithobjocts:@"1",nil];

NSArray *arr3 =  [NSArray alloc];

NSMutbleArray *arr4 =  [NSMutbleArray array];

你會發現:

1、arr2類名叫_NSArray0
2、未init的arr3,類名叫做_NSPlaceHolderArray;
3、初始化後的可變數組類名都叫_NSArrayM;
4、初始化後的不可變數組類名都叫_NSArrayI. 

 

所以做runtime處理的話要謹慎用!

 

IOS 中runtime 不可變數組__NSArray0 和__NSArrayI

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.