问题
Ok. So I had this extremely weird SIGABRT
error on a complex Objective-C iOS program that I'm working on, and after one day of tracking I found the culprit.
Let's say we have the following code:
NSArray *a = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
NSLog(@"tada: %@", [a objectAtIndex:-1]);
Why the hell will this terminate the program with Program received signal: SIGABRT
and the debugger not even pointing to my code (but rather in some assembly part) instead of a nicer 'index out of bounds' and 'hey, this line of code here be wrong' error?
I thought I messed up the project config, so I reproduced this on a brand new project: same result.
Is there a way to configure XCode to be more nice and indicate this kind of errors in a more human understandable way ?
回答1:
As the documentation says:
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
And the default action, when no exception handler is defined, is to... well... you can see what the default behaviour is.
You can use @try/@catch to trap the exception, but that's not really Objective-C-ish. You know how many elements are in the array; there's no real need for you to be accessing elements that don't exist.
Exceptions like this normally have a stack trace, so you can go back to the line of code causing the error. (It might be worth switching between LLDB and GDB if it's not working correctly. LLDB is faster and smaller but not completely reliable.(
回答2:
You should see something along the lines of "index of out range" if you look in the console log in Xcode. SIGABRT is the result of an assertion being fired. Sometimes you have to hit "Continue" after the crash in order to get the message to print.
The debugger tells you where the crash actually happened. It doesn't know what the original cause was. If the debugger leaves you looking at the assembler, just move up the stack until you reach your code.
来源:https://stackoverflow.com/questions/10141196/nsarray-why-is-sigabrt-sent-instead-of-an-index-out-of-bounds-kind-of-error