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

简介:

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

数组越界是非常常见的现象,有时候,你的程序中,因为数组越界而崩溃了,很难找,理想的状态是,数组越界的时候给我们返回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

实现原理超级简单呢:)

使用:

目录
相关文章
|
5月前
|
算法 安全
程序崩溃与优化
程序崩溃与优化
53 0
|
5月前
|
安全 算法 C++
【C++ 异常 】深入了解C++ 异常机制中的 terminate()处理 避免不必要的错误(三)
【C++ 异常 】深入了解C++ 异常机制中的 terminate()处理 避免不必要的错误
112 0
|
1天前
|
存储 安全 Java
如何避免`ArrayStoreException`异常?
`ArrayStoreException`是在Java中尝试将错误类型的对象存储到泛型数组时抛出的异常。要避免此异常,需确保向数组添加的对象类型与数组声明的类型一致,使用泛型和类型检查,以及在运行时进行类型安全的转换和验证。
|
2月前
|
安全 测试技术 数据库连接
如何避免 C# 中的异常
【8月更文挑战第27天】
43 2
|
3月前
|
缓存 算法 Java
JVM内存溢出(OutOfMemory)异常排查与解决方法
JVM内存溢出(OutOfMemory)异常排查与解决方法
|
5月前
|
存储 编译器 程序员
C陷阱——数组越界引发的死循环问题
C陷阱——数组越界引发的死循环问题
|
5月前
|
存储 安全 NoSQL
【C++ 异常 】深入了解C++ 异常机制中的 terminate()处理 避免不必要的错误(二)
【C++ 异常 】深入了解C++ 异常机制中的 terminate()处理 避免不必要的错误
300 1
|
5月前
|
安全 程序员 编译器
【C++ 异常 】深入了解C++ 异常机制中的 terminate()处理 避免不必要的错误(一)
【C++ 异常 】深入了解C++ 异常机制中的 terminate()处理 避免不必要的错误
421 1
|
5月前
|
存储 编译器 C语言
关于数组越界却不会报错
关于数组越界却不会报错
|
编译器 C语言 C++
数组越界访问打印后为什么会陷入死循环
数组越界访问打印后为什么会陷入死循环
89 0