【发布时间】:2013-06-25 23:46:20
【问题描述】:
performSelector:withObject:afterDelay: 有没有可能在子线程中不起作用?
我还是 Objective c 和 Xcode 的新手,所以我可能遗漏了一些明显的东西......:/我真的很感激一些帮助。
我想要做的就是显示一个信息标签 3 秒钟,然后它会被隐藏。如果设置了新信息,则应取消在 3 秒后隐藏标签的线程。 (我不希望通过旧线程隐藏新信息。)
源码:
- (void) setInfoLabel: (NSString*) labelText
{
// ... update label with text ...
infoLabel.hidden = NO;
if(appDelegate.infoThread != nil) [appDelegate.infoThread cancel]; // cancel last hide-thread, if it exists
NSThread *newThread = [[NSThread alloc] initWithTarget: self selector:@selector(setInfoLabelTimer) object: nil];// create new thread
appDelegate.infoThread = newThread; // save reference
[newThread start]; // start thread
[self performSelector:@selector(testY) withObject: nil afterDelay:1.0];
}
-(void) setInfoLabelTimer
{
NSLog(@"setInfoLabelTimer");
[self performSelector:@selector(testX) withObject: nil afterDelay:1.0];
[self performSelector:@selector(hideInfoLabel) withObject: nil afterDelay:3.0];
NSLog(@"Done?");
}
-(void) testX
{
NSLog(@"testX testX testX testX testX");
}
-(void) testY
{
NSLog(@"testY testY testY testY testY");
}
-(void) hideInfoLabel
{
NSLog(@"f hideInfoLabel");
if(!([[NSThread currentThread] isCancelled])) {
AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
appDelegate.infoThread = nil;
appDelegate.infoLabel.hidden = YES;
[NSThread exit];
}
}
控制台输出:
- setInfoLabelTimer
- 完成了吗?
- testY testY testY testY testY
如您所见,performSelector:withObject:afterDelay: 可以工作(--->“testY testY testY testY testY”),但不能在子线程中工作(运行(--->“setInfoLabelTimer”和“Done?”))
有谁知道为什么performSelector:withObject:afterDelay: 在子线程中不起作用? (或者我的错是什么?:()
最好的问候, 茶壶
【问题讨论】:
-
是的,它不起作用。任何与视图相关的东西都必须放在 main 上。
-
.h 中定义的 testx 和 testy 方法?
-
你不应该在后台线程中处理 UIKit 对象。
标签: objective-c selector nsthread