-1

几秒钟后,我正在使用以下代码隐藏 UILabel 。不幸的是,如果用户在 NSInvocation 过程中关闭视图,则应用程序崩溃

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

}

这就是错误

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

我该如何解决?我试过使用

[NSObject cancelPreviousPerformRequestsWithTarget:lblNotification]

在中,- (void)viewDidDisappear:(BOOL)animated但它不起作用。

4

3 回答 3

3

这是你应该如何使用performSelector

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


-(void)hideLabel{
  lblNotification.hidden= YES;
}

或与计时器

[NSTimer scheduledTimerWithTimeInterval:1//1sec
                                 target:self
                               selector:@selector(hideLabel)
                               userInfo:nil
                                repeats:NO];
于 2014-08-01T14:28:23.487 回答
2

你为什么不直接使用dispatch_afer?语法更加清晰:

- (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;
    });
}
于 2014-08-01T14:22:40.893 回答
1

这是因为你在这里传递lblNotification而不是infoc对象:
[NSObject cancelPreviousPerformRequestsWithTarget:lblNotification]

这样做会更好:

- (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];
}
于 2014-08-01T14:30:42.437 回答