-1

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.

Usi Usi
  • 2,967
  • 5
  • 38
  • 69

3 Answers3

3

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];
meda
  • 45,103
  • 14
  • 92
  • 122
2

Why don't you just use dispatch_afer? The syntax is much more clear:

- (void)showStatusBarwithText:(NSString*)text{
    lblNotification.hidden=NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        lblNotification.hidden = YES;
    });
}
Szu
  • 2,254
  • 1
  • 21
  • 37
1

It's because you pass lblNotification instead of infoc object here:
[NSObject cancelPreviousPerformRequestsWithTarget:lblNotification]

It will be better to do this way:

- (void)showStatusBarwithText:(NSString*)text{
    lblNotification.hidden=NO;
    lblNotification.text=text;
    [lblNotification performSelector:@selector(setHidden:) withObject:@(1) afterDelay:2];     
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated]
    [NSObject cancelPreviousPerformRequestsWithTarget:lblNotification];
}
arturdev
  • 10,884
  • 2
  • 39
  • 67