Question

My code is working fine when I call reloadData method every second, it removes the view (when there is a view) and add the subView. The problem is when there is not a subView I get exc_bad_access issue that shows on the [self.lbl1 removeFromSuperview] function.

my code

-(void)reloadData

if (result1 > result2 &&  al == YES)
{
    lbl1 = [[[UILabel alloc] initWithFrame:CGRectMake(320, 530, 550, 200)] autorelease];

    lbl1.userInteractionEnabled = NO;
    lbl1.text = @"WARNING";
    lbl1.tag = 30;
    lbl1.font = [UIFont fontWithName:@"Helvetica" size:18.0];
    lbl1.textColor = [UIColor redColor];
    lbl1.backgroundColor = [UIColor clearColor];
    lbl1.lineBreakMode = NSLineBreakByWordWrapping;
    lbl1.numberOfLines = 2;
    [self addSubview:lbl1];
}

    else if (result1 < result2 &&  al == YES){

    [self.lbl1 removeFromSuperview];
}

Please where would be my issue?

Was it helpful?

Solution

Can there be a condition in your code when the 2nd if loop (result1 < result2 && al == YES) is called before the first one?

In that case, lbl1 would not be added on the view or not be allocated and hence cannot be removed.

You need to check that if lbl1 exists, only then remove it from its superview.

if(self.lbl1) [self.lbl1 removeFromSuperView];

OTHER TIPS

You can also check if the label has the right superview

if (lbl1 && lbl1.superview == self) { // then lbl1 is already a subview of self
    [lbl1 removeFromSuperview];
}

You can check like this in this condition

else if (result1 < result2 &&  al == YES)
{
    for(UIView *view in self.view.subviews)
    {
        if ([view isKindOfClass:[UILabel class]])
        {
            [self.lbl1 removeFromSuperview];
        }
    }
}

try to remove autorelease and make something like

 if (lbl1) {
        [lbl1 removeFromSuperview];
        [lbl1 release];        
    }

before lbl1 = [[[UILabel alloc] initWithFrame...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top