Xcode Objective-C NSArray item - error or app close
I'm totally new to Mac OS and iPhone and I'm writing some small app. I have constant array of image names in resource and I want to switch between these items. I want to display image by the name that is in array (as show below).
However getting the image name string from some index in array seems to cause 3 different errors depending on.. well I don't know on what. Everytime I start app with new Simulator it causes one of 3 errors.
Online materials just show 1) make array 2) add items 3) use objectAtIndex, but it doesn't work for me here. Can't assign string from NSArray to Array.
In header file, inside @interface:
NSMutableArray *imgList;
in code:
imgList = [NSMutableArray arrayWithObjects:@"image01.jpg", @"image02.jpg", @"image03.jpg", nil];
NSString *item;
item = [imgList objectAtIndex:1];
label.text = item
Program randomly has 3 different results for this:
- once console shows no problem but after few function calls app just closes
- other time label.text displays "ca.lproj" - no idea why, it's not part of array
- other time it's console error:
201开发者_开发知识库0-11-24 11:43:15.627 Utility[410:207] -[NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x5f44ba0 2010-11-24 11:43:15.630 Utility[410:207] ** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x5f44ba0' * Call stack at first throw: ( ... ) terminate called after throwing an instance of 'NSException'
Without seeing a bit more of your code is it a trifle difficult to tell, but it looks as if you have forgotten to retain your array. Once the autoreleasepool ticks, you lose the array, and imgList
becomes a dangling pointer; and the memory held by the array becomes overwritten by a string.
Changing [arrayWithObjects:]
to [[alloc] initWithObjects:]
should solve your problem; as should adding a retain
; but it's usually clearer what you are doing if you use the proper allocation methods instead.
精彩评论