• 第17月第7天 iOS 数组越界,防Crash处理


    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

  • 相关阅读:
    腾讯TencentOS正式开放测试:支持“傻瓜式刷机”-android
    glob.h and glob.c for the Android NDK
    (OK) 在CentOS7—编译OpenSSL 静态库—for—Android
    Android
    Pass data to CGI script and back with jQuery.ajax
    yum—repo—How to Enable EPEL Repository for RHEL/CentOS 7/6/5
    裸机版的hello world
    CodeBlock 使用手册
    (NOT OK) How To Build CyanogenMod Android for Motorola Defy ("jordan")
    error: .repo/manifests/: contains uncommitted changes 解决办法
  • 原文地址:https://www.cnblogs.com/javastart/p/8426873.html
Copyright © 2020-2023  润新知