我使用以下代码在几秒钟后隐藏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
但它不起作用。
答案 0 :(得分: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];
答案 1 :(得分: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;
});
}
答案 2 :(得分: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];
}