Custom UIView causes a EXC_BAD_ACCESS code = 1 in layoutSubviews - iphone

I have created a custom UIView which is instantiated 3 times from UIViewController. From the viewDidLoad method of that UIViewController:
self.remainingDays = [[RemainingTileView alloc] initWithFrame:CGRectMake(20, 49, 80, 75)];
self.remainingHours = [[RemainingTileView alloc] initWithFrame:CGRectMake(120, 49, 80, 75)];
self.remainingMinutes = [[RemainingTileView alloc] initWithFrame:CGRectMake(220, 49, 80, 75)];
[self.view addSubview:self.remainingDays];
[self.view addSubview:self.remainingHours];
[self.view addSubview:self.remainingMinutes];
In the RemainingTileView class, I have this layoutSubviews method:
- (void)layoutSubviews {
[super layoutSubviews];
if (self.number) // This is an NSNumber property
self.numberLabel = [self labelForNumber:[self.number intValue]];
else
self.numberLabel = [self labelForNumber:0];
if (self.unit) // This is an NSString property
self.unitLabel = [self labelForUnit:self.unit];
else
self.unitLabel = [self labelForUnit:#""];
[self configView];
}
When creating the view, it crashes on the line if (self.number) with the stack frame:
* thread #1: tid = 0x2403, 0x39f6c526 libobjc.A.dylib`objc_retain + 6, stop reason = EXC_BAD_ACCESS (code=1, address=0x10000010)
frame #0: 0x39f6c526 libobjc.A.dylib`objc_retain + 6
frame #1: 0x000dc742 myProject`-[RemainingTileView layoutSubviews](self=0x1e892b80, _cmd=0x344cde51) + 106 at RemainingTileView.m:63
frame #2: 0x3405d802 UIKit`-[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 258
frame #3: 0x33e07d8a QuartzCore`-[CALayer layoutSublayers] + 214
frame #4: 0x33e07928 QuartzCore`CA::Layer::layout_if_needed(CA::Transaction*) + 460
frame #5: 0x33e0885c QuartzCore`CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 16
frame #6: 0x33e08242 QuartzCore`CA::Context::commit_transaction(CA::Transaction*) + 238
frame #7: 0x33e08050 QuartzCore`CA::Transaction::commit() + 316
frame #8: 0x33e07eb0 QuartzCore`CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 60
frame #9: 0x322276cc CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 20
frame #10: 0x322259c0 CoreFoundation`__CFRunLoopDoObservers + 276
frame #11: 0x32225d16 CoreFoundation`__CFRunLoopRun + 742
frame #12: 0x32198ebc CoreFoundation`CFRunLoopRunSpecific + 356
frame #13: 0x32198d48 CoreFoundation`CFRunLoopRunInMode + 104
frame #14: 0x35d6f2ea GraphicsServices`GSEventRunModal + 74
frame #15: 0x340ae300 UIKit`UIApplicationMain + 1120
frame #16: 0x000d3448 Project Countdown`main(argc=1, argv=0x2fd2ecf8) + 116 at main.m:17
self.number is an instance of NSNumber.
The UI is being modified from the main thread. I have looked for existings solutions here on stackoverflow but nothing worked.
What am I missing? What should I look for?

Looks like your properties have incorrect declarations. Probably assign or weak instead of retain, copy, or strong.

It looks like the property is returning some invalid object and ARC is attempting to retain it, which then fails. It looks like you might be better off moving your check for nil values into a custom property accessor, something along the lines of:
- (NSNumber *)number {
if (_number == nil) {
_number = [NSNumber numberWithInt:0];
}
return _number;
}
Then you can simply set the numberLabel value to number without having to check here. You can do something similar for unit as well.

Related

Adding MKPolyline Overlay to MKMapView crashes application

My application was working fine on iOS6 but it is crashing on iOS 7 due to bad access when I add overlay to MKMapView.My code is as follows
MKPolyline *polyline = [[MKPolyline alloc] init];
polyline = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[directionMap addOverlay:polyline];
This is the crash log
(lldb) bt
*
thread #51: tid = 0x1cc5, 0x38755f8c libdispatch.dylib`dispatch_retain$VARIANT$mp + 8, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
frame #0: 0x38755f8c libdispatch.dylib`dispatch_retain$VARIANT$mp + 8
frame #1: 0x3598dbc8 VectorKit`-[VKRasterOverlayTileSource init] + 176
frame #2: 0x358cfd24 VectorKit`-[VKMapModel _rasterOverlayTileSourceForLevel:] + 308
frame #3: 0x358d0226 VectorKit`-[VKMapModel addRasterOverlay:] + 46
frame #4: 0x2f068dfe MapKit`-[MKOverlayContainerView _insertDrawable:forOverlay:atIndex:level:] + 1010
frame #5: 0x2f06752e MapKit`-[MKOverlayContainerView _configureAndAddDrawable:forOverlay:level:] + 326
frame #6: 0x2f0676ac MapKit`-[MKOverlayContainerView _considerAddingDrawable:inAddRect:level:] + 372
frame #7: 0x2f067cce MapKit`-[MKOverlayContainerView addOverlay:level:] + 246
frame #8: 0x001394c8 Falcon`-[GetDirectionVC showRouteFrom:to:](self=0x19742820, _cmd=0x001fa466, f=CLLocationCoordinate2D at 0x04f9ec2c, t=CLLocationCoordinate2D at 0x04f9ec1c) + 956 at GetDirectionVC.m:226
frame #9: 0x001390ee Falcon`-[GetDirectionVC loadLocations](self=0x19742820, _cmd=0x001fa458) + 1314 at GetDirectionVC.m:173
frame #10: 0x2e876e26 Foundation`__NSThread__main__ + 1062
frame #11: 0x38891c1c libsystem_pthread.dylib`_pthread_body + 140
frame #12: 0x38891b8e libsystem_pthread.dylib`_pthread_start + 102
(lldb)
I had the same problem, the stack trace looks misleading to me. My bugfix is to explicitely add the overlay on the main thread:
dispatch_async(dispatch_get_main_queue(), ^{
[mapView addOverlay:myRouteLine];
});
or if you'd like to use the new MKOverlayRenderer:
dispatch_async(dispatch_get_main_queue(), ^{
[mapView addOverlay:myRouteLine level:MKOverlayLevelAboveRoads];
});
In my case, I'm downloading asynchronously some data, generate Polylines, create MKOverlayViews / MKOverlayRenderes (didn't help to replace the deprecated code) and add the overlay to the map.
Use following If you are creating poly lines in thread other than main thread:
[self performSelectorOnMainThread:#selector(addPolyLineToMap:) withObject:polyline waitUntilDone:NO];
-(void)addPolyLineToMap:(MKPolyline*)apolyline{
[mapview addOverlay:apolyline];
}

How to debug iPhone app crash log. Crash only in App Store purchased version, not in development

I received the first crash report but I am not able to get what is the problem.
Fortunately, since this crash came from a colleague of mine, I can test the error directly on his iPhone and install a development version on his phone.
However, the strange thing is that when I install and run the development version on his device from my computer there is no crash; the crash appear only when the application is downloaded and installed from the App Store.
Until now I could not reproduce the error on any other device (the affected device is an iPhone 3G firmware 4.2.1 and all the operating system run very slowly).
The crash happen after that a row is selected from a UITableViewController (ItemsListTableViewController), at this point a detail view should appear, but the application crash during the construction of the detail view (ItemDetailViewController) in viewDidLoad.
In particular the problem seem to be localized within the class LocationPathView (a subview of ItemDetailViewController's view).
ItemDetailViewController is a subclass of UITableViewController and load its tableHeaderView from nib in viewDidLoad with:
[[NSBundle mainBundle] loadNibNamed:#"ItemDetailHeaderView" owner:self options:nil];
(LocationPathView is part of the tableHeaderView)
When the nib file is loaded, LocationPathView::awakeFromNib is called and then LocationPathView::layoutSubviews is called. The crash seem to be originated from layoutSubviews.
Within layoutSubviews I perform an animation:
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
Could this animation create for some reasons the crash on slow device? Is correct to animate within layoutSubviews?
I would be grateful for any help,
Marco
Date/Time: 2011-04-30 12:50:36.972 +0200
OS Version: iPhone OS 4.2.1 (8C148)
Report Version: 104
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread: 0
Thread 0 Crashed:
0 libSystem.B.dylib 0x35de3ad0 __kill + 8
1 libSystem.B.dylib 0x35de3abe kill + 4
2 libSystem.B.dylib 0x35de3ab2 raise + 10
3 libSystem.B.dylib 0x35dfad5e abort + 54
4 libstdc++.6.dylib 0x374f2a00 __gnu_cxx::__verbose_terminate_handler() + 588
5 libobjc.A.dylib 0x32d9d8d8 _objc_terminate + 160
6 libstdc++.6.dylib 0x374f0100 __cxxabiv1::__terminate(void (*)()) + 76
7 libstdc++.6.dylib 0x374f0178 std::terminate() + 16
8 libstdc++.6.dylib 0x374f02a0 __cxa_throw + 100
9 libobjc.A.dylib 0x32d9bf28 objc_exception_throw + 104
10 CoreFoundation 0x3759dabc +[NSException raise:format:arguments:] + 64
11 CoreFoundation 0x3759daf0 +[NSException raise:format:] + 24
12 QuartzCore 0x33d9409c CALayerSetPosition(CALayer*, CA::Vec2<double> const&, bool) + 180
13 QuartzCore 0x33d93fd8 -[CALayer setPosition:] + 40
14 QuartzCore 0x33d93efc -[CALayer setFrame:] + 444
15 UIKit 0x358d92c8 -[UIView(Geometry) setFrame:] + 248
16 UIKit 0x3592dde0 -[UIButton setFrame:] + 120
17 MyApp 0x0003432a -[LocationPathView layoutSubviews] (LocationPathView.m:101) <<<<<<<<<<<<<<<<<<<<<<<<<<<
18 UIKit 0x358ec704 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 32
19 CoreFoundation 0x37538f72 -[NSObject(NSObject) performSelector:withObject:] + 18
20 QuartzCore 0x33d9a128 -[CALayer layoutSublayers] + 176
21 QuartzCore 0x33d99db0 CALayerLayoutIfNeeded + 192
22 QuartzCore 0x33d99cd8 -[CALayer layoutIfNeeded] + 108
23 UIKit 0x3598ee38 -[UIView(Hierarchy) layoutIfNeeded] + 24
24 UIKit 0x359fbabc -[UIButton titleLabel] + 76
25 MyApp 0x0001fee8 -[ItemDetailViewController viewDidLoad] (ItemDetailViewController.m:148) <<<<<<<<<<<<<<<<<<<<<<<<<<<
26 UIKit 0x35926e58 -[UIViewController view] + 152
27 UIKit 0x35937f2c -[UIViewController contentScrollView] + 24
28 UIKit 0x35937d4c -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 36
29 UIKit 0x35937bf8 -[UINavigationController _layoutViewController:] + 28
30 UIKit 0x35937474 -[UINavigationController _startTransition:fromViewController:toViewController:] + 336
31 UIKit 0x35937288 -[UINavigationController _startDeferredTransitionIfNeeded] + 256
32 UIKit 0x35926c44 -[UINavigationController pushViewController:transition:forceImmediate:] + 904
33 UIKit 0x359268a8 -[UINavigationController pushViewController:animated:] + 36
34 MyApp 0x00020a9a -[ItemsListTableViewController viewItemDetail:startEditable:] (ItemsListTableViewController.m:717)
35 MyApp 0x00022110 -[ItemsListTableViewController tableView:didSelectRowAtIndexPath:] (ItemsListTableViewController.m:241) <<<<<<<<<<<<<<<<<<<<<<<<<<<
36 UIKit 0x3595bf4c -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 884
37 UIKit 0x35a5da9c -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 196
38 Foundation 0x351724d4 __NSFireDelayedPerform + 360
39 CoreFoundation 0x375522fe __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 10
40 CoreFoundation 0x37551cd2 __CFRunLoopDoTimer + 982
41 CoreFoundation 0x37521a8a __CFRunLoopRun + 1178
42 CoreFoundation 0x37521504 CFRunLoopRunSpecific + 220
43 CoreFoundation 0x37521412 CFRunLoopRunInMode + 54
44 GraphicsServices 0x33e76d1c GSEventRunModal + 188
45 UIKit 0x3591d574 -[UIApplication _run] + 580
46 UIKit 0x3591a550 UIApplicationMain + 964
47 MyApp 0x00002fce main (main.m:14)
48 MyApp 0x00002f98 0x1000 + 8088
ItemsListTableViewController.m:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Item *item = [self.fetchedResultsController objectAtIndexPath:indexPath];
[self viewItemDetail:item startEditable:NO]; <<<<<<<<<<<<<<<<<<<
}
- (void)viewItemDetail:(Item *)item startEditable:(BOOL)editable {
ItemDetailViewController *controller = [[ItemDetailViewController alloc] initWithStyle:UITableViewStyleGrouped showItem:item inItemsList:[self.fetchedResultsController fetchedObjects]];
if (editable)
controller.editing = YES;
[self.navigationController pushViewController:controller animated:YES]; <<<<<<<<<<<<<<<<<<<
[controller release];
}
ItemDetailViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = NSLocalizedString(#"Item details", #"Item details");
self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
// Configure the tableview
self.tableView.sectionFooterHeight = 5.0f;
self.tableView.allowsSelectionDuringEditing = YES;
// Create and set the tableview header
if (headerView == nil) {
[[NSBundle mainBundle] loadNibNamed:#"ItemDetailHeaderView" owner:self options:nil]; <<<<<<<<<<<<<<<<<<<<<<<<<<<
// Item title button
itemTitleButton.titleLabel.adjustsFontSizeToFitWidth = YES;
itemTitleButton.titleLabel.minimumFontSize = 11.0f;
[itemTitleButton setImageEdgeInsets:UIEdgeInsetsMake(0.0f, itemTitleButton.bounds.size.width-29.0f, 0.0f, 0.0f)];
[itemTitleButton setTitleEdgeInsets:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 24.0f)];
UIImage *normalImage = [[UIImage imageNamed:#"objectNameHighlighedButton.png"] stretchableImageWithLeftCapWidth:11 topCapHeight:0];
[self.itemTitleButton setBackgroundImage:normalImage forState:UIControlStateHighlighted];
[pathView addTarget:self action:#selector(moveButtonTouchUp:) forControlEvents:UILocationPathViewMoveControlEvent];
// Check if the item's path should be recalculated
if (pathView.pathList == nil) {
pathView.pathList = pathNames;
}
self.tableView.tableHeaderView = headerView;
// Save initial header height so that it can be restore navigating between items with different flags count
tableHeaderFrameHeight = headerView.frame.size.height;
}
// Enable the UIToolbar at the bottom of the view controller and create its buttons
[self.navigationController setToolbarHidden:NO animated:YES];
self.navigationController.toolbar.barStyle = UIBarStyleBlack;
self.navigationController.toolbar.translucent = YES;
// [omitted part]: create toolbar items …
// Restore editing status if the view was unloaded
if (viewUnloaded && self.editing) {
viewUnloaded = NO;
// this will force setEditing:YES to be called on all tableView's subviews! (categorySectionHeaderView...)
[self.tableView setEditing:YES];
// ...not for tableheader!
editableImageView.editing = YES;
pathView.editing = YES;
}
// Recreate item flags
CGRect headerFrame = headerView.frame;
for (FlaggedItem *flagObject in self.itemBookmarkRibbons) {
headerFrame.size.height += ITEM_SHEET_FLAG_BUTTON_HEIGHT + 8.0f;
headerView.frame = headerFrame;
UIButton *bookmarkRibbon = [self createBookmarkRibbon:flagObject];
bookmarkRibbon.frame = CGRectMake(0.0f, headerFrame.size.height-ITEM_SHEET_FLAG_BUTTON_HEIGHT-8.0f,
headerFrame.size.width, ITEM_SHEET_FLAG_BUTTON_HEIGHT);
[headerView addSubview:bookmarkRibbon];
[headerView sendSubviewToBack:bookmarkRibbon];
}
// Update the table header view height
self.tableView.tableHeaderView = headerView;
}
LocationPathView.m:
- (void)awakeFromNib {
[super awakeFromNib];
UIColor *color = [[UIColor alloc] initWithWhite:0.0f alpha:0.0f];
self.backgroundColor = color;
[color release];
[self sendSubviewToBack:backgroundView];
// create imageview rounded rect
CALayer *l = [backgroundView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:10.0];
[l setBorderWidth:2.0];
UIColor *borderColor = [[UIColor alloc] initWithWhite:0.65 alpha:1.0];
[l setBorderColor:[borderColor CGColor]];
[borderColor release];
expanded = NO;
buttons = [[NSMutableArray alloc] initWithCapacity:2];
[buttons addObject:[self createButtonOfType:PVButtonTypeStart]];
[buttons addObject:[self createButtonOfType:PVButtonTypeEnd]];
}
- (void)layoutSubviews {
#define MOVE_BUTTON_WIDTH 90.0f
#define STANDARD_BUTTON_HEIGHT 22.0f
[super layoutSubviews];
CGRect contentRect = self.frame;
if (CGRectIsEmpty(contentRect))
return;
if ([buttons count] != [pathList count] && [pathList count] > 0) {
[self prepareButtons];
}
[UIView beginAnimations:nil context:nil]; <<<<<<<<<<<<<<<<<<<
[UIView setAnimationDuration:0.2];
CGFloat x = 0.0f, y = 0.0f;
CGFloat availableHSpace = 0.0f;
UIButton *button;
for (NSUInteger i=0; i<[self.buttons count]; i++) {
button = [buttons objectAtIndex:i];
if (self.isExpanded == NO && i > 0 && i <= [self.buttons count]-2)
// hide all middle buttons
button.alpha = 0.0f;
else {
button.alpha = 1.0f;
NSString *title = [pathList objectAtIndex:i];
CGSize size = [title sizeWithFont:button.titleLabel.font];
CGFloat buttonWidth = size.width + 36.0f;
// check if the button width is greater than available space, if yes set the button width equal to the available space.
// The available space is reduced in editing move to make room for the move button.
if (self.editing && moveButton)
availableHSpace = contentRect.size.width - MOVE_BUTTON_WIDTH - 3.0f - 10.0f; // 10.0=space from move button
else
availableHSpace = contentRect.size.width;
if (x + buttonWidth > availableHSpace)
buttonWidth = availableHSpace - x;
button.frame = CGRectMake(x, y, buttonWidth, STANDARD_BUTTON_HEIGHT);
[button setTitle:title forState:UIControlStateNormal];
y += STANDARD_BUTTON_HEIGHT + 3.0f; // vertical distance between buttons
}
if (self.isExpanded)
x += 14.0f; // indentation
}
// setup cyan background
backgroundView.alpha = (self.isExpanded ? 0.80f : 0.0f);
CGRect backgroundViewFrame = backgroundView.frame;
if (self.isExpanded) {
// 10.0 = 5.0=y gap between backgroundView and self + 5.0=distance between edge
backgroundViewFrame.size.height = button.frame.origin.y + button.frame.size.height + 12.0f;
}
else
backgroundViewFrame.size.height = self.frame.size.height;
backgroundView.frame = backgroundViewFrame;
[UIView commitAnimations];
// set moveButton position and make it visible (put it out of animation block to avoid frame changing animation,
// fade animation already set from caller)
if (self.editing && moveButton) {
moveButton.frame = CGRectMake(0.0f, 0.0f, MOVE_BUTTON_WIDTH, STANDARD_BUTTON_HEIGHT*2 + 3.0f); // 3.0=vertical space between buttons
moveButton.center = CGPointMake(contentRect.size.width - MOVE_BUTTON_WIDTH/2 - 3.0f, contentRect.size.height/2);
moveButton.hidden = NO;
}
}
Being an error only the app-store version makes me suspicious of a project or target setting used to build the submission binary.
Are you using a project configuration to build the submission binary? If so, the first thing I would look for is a C macro is defined incorrectly for a release version. Or perhaps it is correct at the project-level, but incorrect at the target-level. Perhaps the end of your animation block is not correctly signalled?
Building an ad-hoc version of the app with the exact same settings as your app store version would be a good test. (Code signing would be the only difference.) Delete the old app from the device and deploy it the hard way through iTunes to be sure.
It might be your animation block blocking the main transition running behind. Try to avoid these kind of situation. For example popAviewController and just after push another this kind of situation lead to crash because you are doing another transition before previous one finished. Hope you understand.

Help me ...Terminating app due to uncaught exception 'NSRangeException',

- (void)viewDidLoad {
[super viewDidLoad];
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self selector:#selector(loadImage) object:nil];
[queue addOperation:operation];
[operation release];
NSMutableArray *_array = [[NSMutableArray alloc] initWithCapacity:10000];
self.array = _array;
[_array release];
}
- (void)loadImage
{
for(int i = 0;i < [appDelegate.ArrParseData count]; i++ )
{
NSLog(#" count %i",i);
// Configure the cell...
XMLTags *xmltag = [appDelegate.ArrParseData objectAtIndex:i];
NSString *Img_id, *Img_name, *DynamicImgUrl;
Img_id = xmltag.equip_id;
Img_name = xmltag.image;
DynamicImgUrl = [NSString stringWithFormat:#"http://testetete.com/pics/equipment/%#/%#",Img_id, Img_name];
NSURL *ImageUrl = [NSURL URLWithString:DynamicImgUrl];
NSLog(#" ccxvount %#",ImageUrl);
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:ImageUrl]];
NSLog(#" ccxvount %i",i);
[self.array addObject:image];
NSLog(#" ccxvount %i",i);
}
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UIImageView *top_img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 25, 75, 80)];
CGRect rect = top_img.frame;
rect.size.height = 60;
rect.size.width = 60;
top_img.frame = rect;
// the imageView holds the image myImg
top_img.image = [self.array objectAtIndex:indexPath.row];
//cell.imageView.image=image;
[cell.contentView addSubview:top_img];
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [appDelegate.ArrParseData count];
}
when i excecute the above code my application gets crashes with the following error..
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
*** Call stack at first throw:
(
0 CoreFoundation 0x026cc919 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x0281a5de objc_exception_throw + 47
2 CoreFoundation 0x026c2465 -[__NSArrayM objectAtIndex:] + 261
3 AgSearch 0x00006f80 -[EquipmentViewController tableView:cellForRowAtIndexPath:] + 752
4 UIKit 0x00345a3f -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 619
5 UIKit 0x0033bad2 -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 75
6 UIKit 0x0035040c -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1561
7 UIKit 0x003484bc -[UITableView layoutSubviews] + 242
8 QuartzCore 0x024620d5 -[CALayer layoutSublayers] + 177
9 QuartzCore 0x02461e05 CALayerLayoutIfNeeded + 220
10 QuartzCore 0x0246164c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 302
11 QuartzCore 0x024612b0 _ZN2CA11Transaction6commitEv + 292
12 QuartzCore 0x02468f5b _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 99
13 CoreFoundation 0x026add1b __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 27
14 CoreFoundation 0x02642987 __CFRunLoopDoObservers + 295
15 CoreFoundation 0x0260bc17 __CFRunLoopRun + 1575
16 CoreFoundation 0x0260b280 CFRunLoopRunSpecific + 208
17 CoreFoundation 0x0260b1a1 CFRunLoopRunInMode + 97
18 GraphicsServices 0x02f312c8 GSEventRunModal + 217
19 GraphicsServices 0x02f3138d GSEventRun + 115
20 UIKit 0x002e3b58 UIApplicationMain + 1160
21 AgSearch 0x0000206c main + 102
22 AgSearch 0x00001ffd start + 53
23 ??? 0x00000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
Any help would be greatly appreciated....
Thanks for nay help
does the array has any data when you show the table? if you give a default number of cells that is bigger than 0 and there is no data in the array..then you will receive the error you described.
'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
EDIT:
in
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [appDelegate.ArrParseData count];
}
you shouldn't return the number of elements from the appDelegate.ArrParseData because if that array is filled with data then you will receive a number X bigger than 0.
in the cellForRowAtIndexPath you ask for information at index X but self.array is not filled yet with data because you call the loadImage method async.
You should return [self.array count]; in the numberOfRowsInSection method.
I don't think you are showing all the code you need to show - the trace shows the exception happens some time in cellForRowAtIndexPath. Looks like you are accessing an array that contains nothing - are you completely sure the array has been loaded by the time you try to use it?
Likely you know how many cells there will be and you report that correctly through numberOfRowsInSection, but you haven't populated the array by the time it is required. You need to so something like display placeholders until the load is finished, leave the images nil (empty) until ready, make the data load/view appearance sequential, get the load happening in the background earlier or something like that.
Your number of rows method is accessing a different count array from the one which contains your image, isn't it?
If you executed this code in no concurrent way, you wouldn't have this error. The problem comes when the thread who has to fill in your images array is slower than the main one.
So your best solution would be to check the images array size before accessing it and if you want you could send a reloadRowsAtIndexPaths: withRowAnimation: message to your tableView every time that you get a new image. This would give you a nice loading effect.
I hope I've been clear enough.
See you!
maybe someone make such stupid mistake like me in:
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
and try to do something like this:SomeObject = [SomeContainer objectAtIndex:indexPath]; Or even try to be clever with cast: SomeObject = [SomeContainer objectAtIndex:(int)indexPath]; WRONG
no way...JUST
remember to get index you have to call indexPath.row!!!!!

My application doesn't open after trying to implement iAds!

I have been trying to implement iAds into my application, but this is what happens:
1.Tap on app
2.Loading Screen Displayed for a few seconds
3.App Crashes
This is whats returned:
2010-11-06 20:19:11.043 Vampire Quiz
Final[99722:207] Unknown class
AdViewController in Interface Builder
file. 2010-11-06 20:19:11.066 Vampire
Quiz Final[99722:207]
-[Vampire_Quiz_FinalViewController setBannerIsVisible:]: unrecognized
selector sent to instance 0x761c710
2010-11-06 20:19:11.409 Vampire Quiz
Final[99722:207] * Terminating app
due to uncaught exception
'NSInvalidArgumentException',
reason:
'-[Vampire_Quiz_FinalViewController
setBannerIsVisible:]: unrecognized
selector sent to instance 0x761c710'
* Call stack at first throw: ( 0 CoreFoundation
0x02a88b99 exceptionPreprocess + 185
1 libobjc.A.dylib
0x02bd840e objc_exception_throw + 47
2 CoreFoundation
0x02a8a6ab -[NSObject(NSObject)
doesNotRecognizeSelector:] + 187 3
CoreFoundation
0x029fa2b6 __forwarding + 966 4
CoreFoundation
0x029f9e72 _CF_forwarding_prep_0 + 50
5 Vampire Quiz Final
0x000027a2
-[Vampire_Quiz_FinalViewController viewDidLoad] + 601 6 UIKit
0x003715ca -[UIViewController view] +
179 7 Vampire Quiz Final
0x000021b1
-[Vampire_Quiz_FinalAppDelegate application:didFinishLaunchingWithOptions:]
+ 74 8 UIKit 0x002c7f27 -[UIApplication
_callInitializationDelegatesForURL:payload:suspended:]
+ 1163 9 UIKit 0x002ca3b0 -[UIApplication
_runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:]
+ 346 10 UIKit 0x002d43ec -[UIApplication
handleEvent:withNewEvent:] + 1958 11
UIKit
0x002ccb3c -[UIApplication sendEvent:]
+ 71 12 UIKit 0x002d19bf _UIApplicationHandleEvent +
7672 13 GraphicsServices
0x03368822 PurpleEventCallback + 1550
14 CoreFoundation
0x02a69ff4
CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION
+ 52 15 CoreFoundation 0x029ca807 __CFRunLoopDoSource1 + 215
16 CoreFoundation
0x029c7a93 __CFRunLoopRun + 979 17
CoreFoundation
0x029c7350 CFRunLoopRunSpecific + 208
18 CoreFoundation
0x029c7271 CFRunLoopRunInMode + 97 19
UIKit
0x002c9c6d -[UIApplication _run] + 625
20 UIKit
0x002d5af2 UIApplicationMain + 1160
21 Vampire Quiz Final
0x00002144 main + 102 22 Vampire
Quiz Final 0x000020d5
start + 53 ) terminate called after
throwing an instance of 'NSException'
sharedlibrary apply-load-rules all
(gdb)
P.S. I am new to development on the iPhone
Thanks
This is my code :
#implementation Vampire_Quiz_FinalViewController
- (IBAction)V;
{
Vork *V = [[Vork alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:V animated:NO];
}
- (IBAction)A;
{
About *A = [[About alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:A animated:NO];
}
- (IBAction)I;
{
Instructions *I = [[Instructions alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:I animated:NO];
}
- (void)dealloc {
[super dealloc];
}
- (void)viewDidLoad {
adView = [[ADBannerView alloc] initWithFrame:CGRectZero];
adView.frame = CGRectOffset(adView.frame, 0, -50);
adView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifier320x50];
adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
[self.view addSubview:adView];
adView.delegate=self;
self.bannerIsVisible=NO;
[super viewDidLoad];
}
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
if (!self.bannerIsVisible)
{
[UIView beginAnimations:#"animateAdBannerOn" context:NULL];
// banner is invisible now and moved out of the screen on 50 px
banner.frame = CGRectOffset(banner.frame, 0, 50);
[UIView commitAnimations];
self.bannerIsVisible = YES;
}
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
if (self.bannerIsVisible)
{
[UIView beginAnimations:#"animateAdBannerOff" context:NULL];
// banner is visible and we move it out of the screen, due to connection issue
banner.frame = CGRectOffset(banner.frame, 0, -50);
[UIView commitAnimations];
self.bannerIsVisible = NO;
}
}
#end
How can I fix it???
you are using self.bannerIsVisible but I can't see neither a synthesize for this nor setters and getters. Did you made a property with bannerIsVisible in your .h file?
To resolve this crash you should define the property in you header and add a #synthesize statement in your implementation.
Maybe you should start with something more basic to get to know the fundamental things like properties, synthesizers, compiler warnings (there should be one), debugging, and so on.
I don't want to be rude, but you won't learn much by using copied code you don't understand.
unrecognized selector sent to instance: this means the method for that class is not found. Check the class implementation.

How to ensure that UIImage is never released?

I grabbed the crash log from the iPhone:
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000c
Crashed Thread: 0
Thread 0 Crashed:
0 libobjc.A.dylib 0x30011940 objc_msgSend + 20
1 CoreFoundation 0x30235f1e CFRelease + 98
2 UIKit 0x308f4974 -[UIImage dealloc] + 36
3 CoreFoundation 0x30236b72 -[NSObject release] + 28
4 UIKit 0x30a00298 FlushNamedImage + 64
5 CoreFoundation 0x30250a20 CFDictionaryApplyFunction + 124
6 UIKit 0x30a0019c _UISharedImageFlushAll + 196
7 UIKit 0x30a00730 +[UIImage(UIImageInternal) _flushCacheOnMemoryWarning:] + 8
8 Foundation 0x3054dc7a _nsnote_callback + 178
9 CoreFoundation 0x3024ea52 _CFXNotificationPostNotification + 298
10 Foundation 0x3054b854 -[NSNotificationCenter postNotificationName:object:userInfo:] + 64
11 Foundation 0x3054dbba -[NSNotificationCenter postNotificationName:object:] + 14
12 UIKit 0x30a00708 -[UIApplication _performMemoryWarning] + 60
13 UIKit 0x30a006a0 -[UIApplication _receivedMemoryNotification] + 128
14 UIKit 0x30a005d0 _memoryStatusChanged + 56
15 CoreFoundation 0x30217410 __CFNotificationCenterDarwinCallBack + 20
16 CoreFoundation 0x3020d0aa __CFMachPortPerform + 72
17 CoreFoundation 0x30254a70 CFRunLoopRunSpecific + 2296
18 CoreFoundation 0x30254164 CFRunLoopRunInMode + 44
19 GraphicsServices 0x3204529c GSEventRunModal + 188
20 UIKit 0x308f0374 -[UIApplication _run] + 552
21 UIKit 0x308eea8c UIApplicationMain + 960
...
...
From my previous question, Can somebody give me a hand about this stacktrace in iPhone app?, I have changed my codes mainly around UIImage part. I now use [[UIImage alloc] initWithContentsOfFile ... ]. No more [UIImage imageNamed: ... ] or the like. The portion is below.
//this is a method of a subclass of UIImageView.
- (void) reviewImage: (bool) review{
NSString* st;
if (review){
NSString* origin = [NSString stringWithString: [[ReviewCardManager getInstance] getCardImageString:chosenIndex]];
NSString* stt = [origin substringToIndex: [origin length]-4];
st = [[NSString alloc] initWithString: stt];
if (myImageFlipped == nil)
myImageFlipped = [[UIImage alloc] initWithContentsOfFile: [[NSBundle mainBundle] pathForResource:st ofType:#"png"]];
[self setImage:myImageFlipped];
if (notRotated){
self.transform = CGAffineTransformRotate(self.transform, [MyMath radf:rotate]);
notRotated = false;
}
}else{
st = [[NSString alloc] initWithFormat:#"sc%d", chosenNumber];
if (myImage == nil)
myImage = [[UIImage alloc] initWithContentsOfFile: [[NSBundle mainBundle] pathForResource:st ofType:#"png"]];
[self setImage:myImage];
if (notRotated){
self.transform = CGAffineTransformRotate(self.transform, [MyMath radf:rotate]);
notRotated = false;
}
}
[st release];
}
I also have the UIImage already retained in the property.
#property (nonatomic, retain) UIImage* myImage, *myImageFlipped;
Memory Leaks have also been taken cared of. These variables are release in dealloc method.
I thought that I have successfully killed the bug, but it seems that I still have a rare occuring bug problem.
Based on the crash log, my application yells out "performMemoryWarning". I am just "alloc"-ing 13 .png images with the size 156 x 272. I'm confused. Those images shouldn't take that much memory to the point that it exceeds iPhone's RAM. Or is there something I am overlooking? Please advise.
To help you with memory issues and UIImages, you might want to use the imageNamed convience method of UIImage, from the docs:
This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.
Alternatively, you might want to go this route if you still run into memory issues after switching to UIImage imageNamed, because there are some downsides to using the convinience method.
The problem is solved. I forgot to change UIImage at one place. Now, all UIImages are truly "alloc", no more autorelease.
FYI, if you are using [UIImage imageNamed: ... ], use "Simulate Memory Warning" on iPhone Simulator to see whether you are having a problem with it when the real device is low on memory.