第17月第7天 iOS 數組越界,防Crash處理

來源:互聯網
上載者:User

標籤:越界   --   bsp   cto   sele   art   不可變   article   exception   

1.

上面方法已經可以避免crash,為了避免冗餘的代碼,寫一個NSArray的分類,利用runtime替換NSArray的對象方法objectAtIndex:,在這裡進行判斷,捕獲異常:#import <Foundation/Foundation.h>@interface NSArray (Crash)@end/*** ---------------分割線--------------- ***/ #import "NSArray+Crash.h"#import <objc/runtime.h>@implementation NSArray (Crash)+ (void)load{    [super load];        //替換不可變數組方法    Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));    Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtSafeIndex:));    method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);        //替換可變數組方法    Method oldMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:));    Method newMutableObjectAtIndex =  class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(mutableObjectAtSafeIndex:));    method_exchangeImplementations(oldMutableObjectAtIndex, newMutableObjectAtIndex);}- (id)objectAtSafeIndex:(NSUInteger)index{    if (index > self.count - 1 || !self.count) {        @try {            return [self objectAtSafeIndex:index];        }        @catch (NSException *exception) {            NSLog(@"exception: %@", exception.reason);            return nil;        }            }else {        return [self objectAtSafeIndex:index];    }}- (id)mutableObjectAtSafeIndex:(NSUInteger)index{    if (index > self.count - 1 || !self.count) {        @try {            return [self mutableObjectAtSafeIndex:index];        }        @catch (NSException *exception) {            NSLog(@"exception: %@", exception.reason);            return nil;        }            }else {        return [self mutableObjectAtSafeIndex:index];    }}@end

http://blog.csdn.net/hero_wqb/article/details/78531218

 

第17月第7天 iOS 數組越界,防Crash處理

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.