gpt4 book ai didi

iPhone ios线程问题: delegate object not responding when using dispatch_async

转载 作者:行者123 更新时间:2023-12-03 19:59:49 26 4
gpt4 key购买 nike

这是我的代码:

MainDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
FetchManager *fetchManager = [FetchManager sharedInstance];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^{
[fetchManager fetchData];
});

//regular code continues

}

FetchData.m(这是一个单例类)

- (id)getInstance { ... }

- (void)fetchData
{
NSURL *url = [NSURL URLWithString:@"http://www.data.xml"];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];

if (connectionInProgress) {
[connectionInProgress cancel];
[connectionInProgress release];
}

[xmlData release];
xmlData = [[NSMutableData alloc] init];

connectionInProgress = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}

/*and all necessary NSXMLParserDelegate protocol methods are implemented - not shown here*/

问题:没有触发任何 NSXMLParserDelegate 协议(protocol)方法。我不知道为什么。如果我删除 didFinishLaunchingWithOptions 方法中的“dispatch_async”,那么事情就会按预期工作 - NSXMLParserDelegate 协议(protocol)方法被触发。

有人发现问题了吗?

最佳答案

有两件事跳出来:

  1. NSURLConnection 需要运行循环才能运行。当您在主线程上运行时,会自动出现一个运行循环,连接将在该循环上自行调度。当您使用dispatch_async()时,您的 block 被安排在某个辅助线程中,该辅助线程可能没有运行循环,或者其运行循环可能不处于允许NSURLConnection运行的模式。

  2. 即使连接可以自行调度, block 也会在连接创建后立即结束。 NSURLConnection 期望在创建它的线程上发送其委托(delegate)消息,但是如果 block 已经结束,那将如何工作?是否存在某种有效的上下文,可以在该线程上调用委托(delegate)?

关于iPhone ios线程问题: delegate object not responding when using dispatch_async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5201785/

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