如何處理數組越界而不會讓程序崩潰?
數組越界是非常常見的現象,有時候,你的程序中,因為數組越界而崩潰了,很難找,理想的狀態是,數組越界的時候給我們返回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
實現原理超級簡單呢:)
使用: