如何处理数组越界而不会让程序崩溃?

如何处理数组越界而不会让程序崩溃?

数组越界是非常常见的现象,有时候,你的程序中,因为数组越界而崩溃了,很难找,理想的状态是,数组越界的时候给我们返回nil就好了.

请看下面这个例子:

//
//  RootViewController.m
//  BeyondTheMark
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 测试用array
    NSArray *testArray = @[@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7"];
    
    // 结果
    NSLog(@"%@", [testArray objectAtIndex:8]);
}

@end

运行结果:

2014-07-10 10:16:40.044 BeyondTheMark[7248:60b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 8 beyond bounds [0 .. 7]'
*** First throw call stack:
(0x30714fd3 0x3ae5fccf 0x3064ba89 0x741cf 0x32f354cb 0x32f35289 0x32f3bed9 0x32f39847 0x32fa335d 0x73e31 0x32fa05a7 0x32f9fefb 0x32f9a58b 0x32f36709 0x32f35871 0x32f99cc9 0x3556baed 0x3556b6d7 0x306dfab7 0x306dfa53 0x306de227 0x30648f0f 0x30648cf3 0x32f98ef1 0x32f9416d 0x7403d 0x3b36cab7)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

这个方法objectAtIndex:的说明

- (id)objectAtIndex:(NSUInteger)index
Description    
Returns the object located at the specified index.
If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.超出了界限就会抛出异常
Parameters    
index    
An index within the bounds of the array.

我们可以写一个类目来避免数组越界后直接崩溃的情形(或许崩溃是最好结果,但我们有时候可以直接根据判断数组取值为nil避免崩溃),代码如下:

//
//  NSArray+YXInfo.h
//  BeyondTheMark
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSArray (YXInfo)

- (id)objectAt:(NSUInteger)index;

@end
//
//  NSArray+YXInfo.m
//  BeyondTheMark
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import "NSArray+YXInfo.h"

@implementation NSArray (YXInfo)

- (id)objectAt:(NSUInteger)index
{
    if (index < self.count)
    {
        return self[index];
    }
    else
    {
        return nil;
    }
}

@end

实现原理超级简单呢:)

使用:

原文地址:https://www.cnblogs.com/YouXianMing/p/3835209.html