博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何处理数组越界而不会让程序崩溃?
阅读量:6873 次
发布时间:2019-06-26

本文共 1976 字,大约阅读时间需要 6 分钟。

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

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

实现原理超级简单呢:)

使用:

 

 

转载地址:http://tsofl.baihongyu.com/

你可能感兴趣的文章
LeetCode 227 Basic Calculator II
查看>>
JavaScript常用脚本集锦4
查看>>
Yeoman(Yo、Grunt、Bower)——前端工程化-新手之路1
查看>>
在OS X上配置Clojure开发环境
查看>>
iOS开发小技巧总结20150318
查看>>
day18_文件的上传和下载学习笔记
查看>>
介绍几个python的音频处理库
查看>>
架构选型必读:集中式与分布式全方位优劣对比
查看>>
求两数之和
查看>>
JAVA的POI操作Excel
查看>>
分布式事务--消息发送一致性(可靠消息的前提保障)
查看>>
AbleCloud与鸿雁电器携手,领跑智能家居,打造智慧城市
查看>>
kubernetes 基本概念
查看>>
Python用5000+条数据为你分析《我不是药神》登顶原因!(附代码)
查看>>
Android 面试(六):你已经用 SharedPrefrence 的 apply() 替换 commit() 了吗?
查看>>
第82天:jQuery中prop()和attr()的区别
查看>>
一入前端深似海,从此红尘是路人系列第十弹之如何合理利用Git进行团队协作(一)...
查看>>
数据库实践如何解决互联网架构转型中的痛点!
查看>>
OpenCV使用python实现限制对比度的自适应直方图均衡化
查看>>
浪潮“计算+”:聚焦三大计算,打造数据社会原动力
查看>>