user519274
user519274

Reputation: 1144

ios adding an object as subview and releazing give EXC_BAD_ACCESS exception , why?

I have a simple application where i add UIButton programmatically as follow

    for(int i=0;i<[self.contentList count];i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button addTarget:self action:@selector(buttonSelection:)forControlEvents:UIControlEventTouchDown];
        [button setTitle:[ [contentList objectAtIndex:i] valueForKey:@"nameKey"]  forState:UIControlStateNormal];
        button.tag=i+kButtonTagOffset;
        [self.view insertSubview:button atIndex:0];
       // [button release];

    }

Then Accessing it when view change its orientation as follow to adjust its position as follow

  for (int row = 0; row < Portrait_TILE_ROWS; ++row)
    {
        for (int col = 0; col < Portrait_TILE_COLUMNS; ++col)
        {
            int index = (row * Portrait_TILE_COLUMNS) + col;
            CGRect frame = CGRectMake(LandScape_TILE_MARGIN + col * (LandScape_TILE_MARGIN + LandScape_TILE_WIDTH),
                                      LandScape_TILE_MARGIN + row * (LandScape_TILE_MARGIN + LandScape_TILE_HEIGHT),
                                      LandScape_TILE_WIDTH, LandScape_TILE_HEIGHT);

            UIButton *tmb= (UIButton *)[self.view viewWithTag:index+kButtonTagOffset];
            if([tmb isKindOfClass:[UIButton class]]) //isKindOfClass
            {   
                [  [self.view viewWithTag:index+kButtonTagOffset] setFrame:frame];

            }

        }
    }

My First question is why i get EXC_BAD_ACCESS error if i release the UIBUtton after adding to subview and it only happens on the device not the simulator .I thought when adding to a subview the retain count of the objects goes up by one and accessing it later won't raise that ERROR any idea ?

How i can figure out within the xcode debugger what object and where that EXC_BAD_ACCESS exception is raised i figured it out by simply commenting parts of the code !!!

Thanks M

Upvotes: 0

Views: 369

Answers (1)

borrrden
borrrden

Reputation: 33421

You need to reread the basics of memory management and cocoa naming conventions. You didn't call alloc, copy, or retain on it...so releasing it is incorrect. That constructor returns an autoreleased object. If this concept is difficult for you, please switch to ARC.

As for figuring out which line the error is on -> "Run > Stop on Objective-C exception" in Xcode 4?

Upvotes: 1

Related Questions