iosobjective-cuilabelnsinvocationoperation

Hide a UIlabel after some seconds


I'm using this following code to hide a UILabel after some seconds. Unfortunately if the user close the view during the NSInvocation is in progress the app crashes

- (void)showStatusBarwithText:(NSString*)text{
    lblNotification.hidden=NO;
    NSInvocation* invoc = [NSInvocation invocationWithMethodSignature:[lblNotification methodSignatureForSelector:@selector(setHidden:)]];
    [invoc setTarget:lblNotification];
    [invoc setSelector:@selector(setHidden:)];
    lblNotification.text=text;
    BOOL yes = YES;
    [invoc setArgument:&yes atIndex:2];
    [invoc performSelector:@selector(invoke) withObject:nil afterDelay:1];

}

and that's the error

 *** -[UILabel setHidden:]: message sent to deallocated instance 0x1a8106d0

How can I solve? I have tried using

[NSObject cancelPreviousPerformRequestsWithTarget:lblNotification]

In the - (void)viewDidDisappear:(BOOL)animated but it doesn't work.


Solution

  • Here is how you should use performSelector

    - (void)showStatusBarwithText:(NSString*)text{
       lblNotification.hidden=NO;
       [self performSelector:@selector(hideLabel) withObject:nil afterDelay:1];//1sec
    }
    
    
    -(void)hideLabel{
      lblNotification.hidden= YES;
    }
    

    or with the timer

    [NSTimer scheduledTimerWithTimeInterval:1//1sec
                                     target:self
                                   selector:@selector(hideLabel)
                                   userInfo:nil
                                    repeats:NO];