NSMutableArray - App runs in simulator but not on device
My app runs fine in the simulator, but when running on the device, it terminates with SIGABRT. I have narrowed it down to the following code:
- (void)loadImage {
int imageNumber = currentImageNumber;
// check to see if the image has already been downloaded.
// if not, get it and add it to an array
if ([imageData开发者_如何转开发 count] < totalNumberOfImages && (imageNumber + 1) > [imageData count]) {
NSString *urlString = [[mainMenuItem.imageDetails objectAtIndex: imageNumber] objectForKey: @"url"];
NSURL *url = [NSURL URLWithString: urlString];
NSData *data = [NSData dataWithContentsOfURL: url];
UIImage *image = [UIImage imageWithData: data];
[imageData addObject: image];
}
// set the image from the array
self.imageOnScreen = [imageData objectAtIndex: imageNumber];
}
It is the [imageData addObject:image]; message that generates the crash, with the following console output:
2010-09-17 00:03:03.005 PilotsMate[17426:5e03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'
*** Call stack at first throw:
(
0 CoreFoundation 0x313f4fd3 __exceptionPreprocess + 114
1 libobjc.A.dylib 0x3302f8a5 objc_exception_throw + 24
2 CoreFoundation 0x31377f99 -[__NSArrayM insertObject:atIndex:] + 472
3 CoreFoundation 0x31377da7 -[__NSArrayM addObject:] + 34
4 PilotsMate 0x00007c5d -[WeatherDetailViewController loadImage] + 300
5 PilotsMate 0x00007eb1 -[WeatherDetailViewController displayPicture:] + 232
6 Foundation 0x33265c9d -[NSThread main] + 44
7 Foundation 0x332ea9e1 __NSThread__main__ + 972
8 libSystem.B.dylib 0x3527598d _pthread_start + 248
9 libSystem.B.dylib 0x3526b0ec thread_assign_default + 4294967295
)
terminate called after throwing an instance of 'NSException'
[Switching to thread 11523]
[Switching to thread 11523]
Program received signal: “SIGABRT”.
kill
What is causing this, since there are no issues in the simulator? I'm very puzzled and would appreciate your input. All I am doing is initialising an NSMutableArray in viewDidLoad and then adding an object to the array. If I clean the targets, there is no change to what happens. Weird, because this part of the app ran fine a few days ago and I've not modified this implementation file at all (nor have I updated to the newest iOS 4.1 yet, so there is no change to the OS or Xcode version either).
The error message you pasted says it all:
[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0
The image
object is nil
. Why is it nil
? Set a breakpoint in Xcode while running it in the Simulator and figure out which line above it in the culprit.
To elaborate on Shaggy Frog's answer, I think the most likely reason for image to be nil is if there is a problem reading from the URL. Try using dataWithContentsOfURL:options:error: and checking the outputted error to see what happened.
精彩评论