gpt4 book ai didi

objective-c - iOS:performSelectorOnBackground/MainThread:不更新标签

转载 作者:行者123 更新时间:2023-11-28 20:26:27 25 4
gpt4 key购买 nike

我有一个 while 语句在后台运行。

- (IBAction)startButton
{
[self performSelectorInBackground:@selector(Counter) withObject:nil];
.....
}

- (void) Counter
{
while (round) {
if (condition)
{
NSString *str;
str = [NSString stringWithFormat:@"%d",counter];
[self performSelectorOnMainThread:@selector(updateLabel:) withObject:str waitUntilDone:NO];
}
}
}
- (void)updateLabel: (NSString*) str
{
[self.label setText:str];
NSLog(@"I am being updated %@",str);
}

NSlog 为我提供了正确的更新值,但标签从未更新。

我做错了什么?

更新:

标签已连接,在 while 语句完成后更新。

我也已经初始化了标签。

- (void)viewDidLoad
{ [super viewDidLoad];
label.text = @"0";
}

最佳答案

检查 IBOutlet 是否在 Interface Builder 中连接

编辑 3

尝试使用 GCDdispatch_async 来分派(dispatch)请求,所以它变成了

while (round) {
if (condition)
{
NSString * str = [NSString stringWithFormat:@"%d",counter];
dispatch_async(dispatch_get_main_queue(),^ {
[self updateLabel:str];
});
}
}

另一种更新 UILabel 的方法是设置一个 NSTimerx 秒更新一次(根据您的需要),而不是用 while 循环。

应该是这样的

NSTimer * updateLabelTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];

-(void)updateLabel {
if(condition) {
self.label.text = [NSString stringWithFormat:@"%d", counter];
}
}

关于objective-c - iOS:performSelectorOnBackground/MainThread:不更新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13749444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com