Usi Usi
Usi Usi

Reputation: 2997

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.

Upvotes: -1

Views: 1950

Answers (3)

arturdev
arturdev

Reputation: 11039

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];
}

Upvotes: 1

meda
meda

Reputation: 45500

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];

Upvotes: 3

Szu
Szu

Reputation: 2252

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;
    });
}

Upvotes: 2

Related Questions