开发者

objectAtIndex returns SIGABRT error

开发者 https://www.devze.com 2023-03-08 17:18 出处:网络
I have this line: NSString *objectkey=[NSString stringWithFormat:@\"%@\",[line objectAtIndex:1]]; If objectAtIndex:0, it works fine. But if 1, it produces SIGABRT error at runtime.

I have this line:

 NSString *objectkey=[NSString stringWithFormat:@"%@",[line objectAtIndex:1]];

If objectAtIndex:0, it works fine. But if 1, it produces SIGABRT error at runtime.

However, I have another line to confirm that the array "line" has an object at index 1:

   NSLog(@"%d",[line count]);

This returns 2 to the console.

Why would SIGABRT occur even though an index should exist there?

As for line, it is created like this:

for (int i=1;i<=[components count];i++){

    NSArray*line=[[components objectAtIndex:(i-1)] componentsSeparatedByString:@"|"];

"line" is recreated during each loop iteration (I assume this is okay? no release is necessary, from what i understand using the "separated by string" method).

the array "components" contains lines such as:

Recipe Books|BOOKS

Recipe Photos|PHOTOS

I have created this little loop to verify that开发者_如何学Go all are strings in "line":

 for( NSObject* obj in line )
    {
        NSLog(@"%@",obj);
        if ([obj isKindOfClass:[NSString class]]==YES) { NSLog(@"string"); }
    }


Most likely the object contained at [line objectAtIndex:1] is not an NSString*. Why don't you try iterating over the set of objects in line and outputting them with NSLog. My guess is that the second one is going to print an address (of the form <Classname: 0x0>, not a string.

for( NSObject* obj in line )
{
   NSLog(@"%@",obj);
}

Add an NSLog to the code where you create line:

for (int i=1;i<=[components count];i++){
    NSLog(@"%@",[components objectAtIndex:(i-1)]);
    NSArray*line=[[components objectAtIndex:(i-1)] componentsSeparatedByString:@"|"];

I have a strong feeling that your input data is bad, as you've excluded our prior answers as the solution with your responses. Your input data might have a <cr> somewhere it doesn't belong or missing data. How big is the input file for components?


Second answer based on gdb results

Try using [NSString stringWithString:[line objectAtIndex:1]] instead of stringWithFormat. Based on your use of gdb its likely that stringWithFormat is breaking on the unexpected control character (and trying to format it). stringWithString should copy the string character by character. Removing the control character(s) is another problem. :)


Assuming there is a valid object at index 1 of your line NSArray, the likely answer is that it's not a NSString, it's some other class that can't be translated using %@ in your stringWithFormat: call. Look at the stack where it aborts and you could also check the type of the object before calling the stringWithFormat: call.

0

精彩评论

暂无评论...
验证码 换一张
取 消