gpt4 book ai didi

iOS Objective-C 相当于 Win32 PeekMessage/Translate/Dispatch

转载 作者:行者123 更新时间:2023-11-29 00:29:10 51 4
gpt4 key购买 nike

在 Windows 中,可以在代码中运行事件 ..

//PeekMessage loop example
while (WM_QUIT != uMsg.message)
{
while (PeekMessage (&uMsg, NULL, 0, 0, PM_REMOVE) > 0) //Or use an if statement
{
TranslateMessage (&uMsg);
DispatchMessage (&uMsg);
}
}

在 iOS 的 Objective-C 中,是否有一种方法可以间歇性地运行事件,例如,for 循环?

我有一些嵌套很深的代码需要一些时间才能运行,我希望它能间歇性地更新进度。重新设计深层嵌套的代码并不是真正的选择,它可以在其他操作系统上运行。

最佳答案

所以,您基本上想要运行一个长任务并相应地更新进度。这可以通过 Objective-C 中的 GCDNSOperationQueue 来完成。下面的代码为您提供了一个示例。

在这里,我将使用一个将 block 作为输入的函数。该函数包含异步代码。

typedef void(^ProgressBlock)(CGFloat progress); // defined block

- (void)executeTaskWithProgress:(ProgressBlock)progress; // defined function

您可以通过以下两种方式异步运行您的任务:

  1. 使用GCD:

    - (void)executeTaskWithProgress:(ProgressBlock)progress {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    // your long running task

    // the below line is for updating progress
    dispatch_async(dispatch_get_main_queue(), ^{
    progress(20.0);
    });
    });
    }
  2. 使用NSOperation:

    - (void)executeTaskWithProgress:(ProgressBlock)progress {

    NSOperationQueue *executionQueue = [[NSOperationQueue alloc] init];
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
    // your long running task

    // the below line is for updating progress
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    progress(20.0);
    }];
    }];

    [executionQueue addOperation:operation];
    }

您可以通过以下方式调用该函数:

[self executeTaskWithProgress:^(CGFloat progress) {
[self.myLabel setText:[NSString stringWithFormat:@"%f completed", progress]];
// myLabel is an UILabel object
}];

有关在 Objective-C 中使用 GCD 进行异步编程的更多详细信息,我建议您查看以下 tutorial .有任何疑问欢迎提问

关于iOS Objective-C 相当于 Win32 PeekMessage/Translate/Dispatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316289/

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