gpt4 book ai didi

ios - 在 iOS 上使用 Grand Central Dispatch,如果常规 Objective-C block 不在调度队列中,它们会在哪个队列(如果有)上运行?

转载 作者:行者123 更新时间:2023-12-01 19:00:28 25 4
gpt4 key购买 nike

下面的选项#1 是否运行某种隐含队列?它似乎没有在主队列上运行,因为当我尝试在那里更新 UI 内容时它一直提示,直到我移至选项 #3,所以我假设 block 有自己的队列或线程?在它提示之前,我的印象是,如果我不启动调度队列,事情就会像往常一样运行,在我看来,它会在主队列上。下面是一些示例代码来说明:

// UserViewController.h
@interface UserViewController : NSObject
@property(nonatomic, strong) Server *server;
@property(nonatomic, strong) User *user;
@end

// UserViewController.m - Controller that sets a block for use in another class
@implementation UserViewController
- (void)doSomething {
// I'd like to call other methods and set @properties from the controller and I've heard
// __weak is the correct keyword to use (rather than __block or __strong).
__weak UserViewController *weakController = self;

// Option #0 - Outside of block
weakController.user = [[RHZUser alloc] init];

server.callbackBlock = ^(NSURLResponse *response, NSData *data, NSError *error) {

// Option #1 - Outside of dispatch queues. Is this in some sort of default queue?
weakController.user = [[RHZUser alloc] init];

dispatch_queue_t backgroundQueue
= dispatch_queue_create("com.example.backgroundQueue", nil);

dispatch_async(backgroundQueue, ^{

// Option #2 - This is on the serial queue I created
weakController.user = [[RHZUser alloc] init];

dispatch_async(dispatch_get_main_queue(), ^{

// Option #3 - The main queue where all my UI is
weakController.user = [[RHZUser alloc] init];

} // dispatch_async
} // dispatch_async
}; // self.callbackBlock
}
@end

// Server.m - Class that uses the block defined in the controller
@implementation Server
- makeAServerCall {
[NSURLConnection sendAsynchronousRequest:
[NSMutableURLRequest requestWithURL:restServiceURL]
queue:[[NSOperationQueue alloc] init]
completionHandler:self.callbackBlock];
}
@end

最佳答案

block 是一段代码,当执行时,它会在特定队列上运行。在某个对象上设置 block 不会使其运行,也不会附加到一个特定的队列。
对于选项 1,您在 Server 的实例上设置了 block 属性。 .这并不意味着它已经运行,它所做的只是让任何有权访问该 block 的人都可以访问该代码。因为属性的名字是callbackBlock , 我假设 Server实例在完成某事时执行该 block 。
那是 当 block 被绑定(bind)到队列时。 Server的实现决定它是否在主队列上运行,并且应该记录(可能在其 .h 中)它是否运行。如果它没有记录在案,但我绝对需要它在主队列上运行,我总是安全地使用它,并通过将它包装在 dispatch_async 中来确保它在主线程上被调用。 .
编辑:
假设您的 Server实现与 Server 相同的,您使用 alloc/init 创建一个新队列并将其传递给 NSURLConnection .来自 NSURLConnection文档:

queue

The operation queue to which the handler block is dispatched when the request completes or failed.


因此,确实记录了该行为,如果您希望在主队列上调用处理程序,只需传递 dispatch_get_main_queue .

关于ios - 在 iOS 上使用 Grand Central Dispatch,如果常规 Objective-C block 不在调度队列中,它们会在哪个队列(如果有)上运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23257629/

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