gpt4 book ai didi

objective-c - iOS:CFRunLoopRun() 函数困惑

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:47 24 4
gpt4 key购买 nike

我读过有关 CFRunLoop 的内容,但仍然对它有些困惑。我遇到了一段代码,我想自己澄清一下:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:url]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
[[NSURLConnection alloc]initWithRequest:request delegate:self];

CFRunLoopRun();

那么,假设这一切都在主线程上调用,它会阻塞主线程吗?或者它会通过 CFRunLoopRun() 函数调用产生一个新线程吗?

谢谢!

最佳答案

其实有一种情况是有道理的。在创建递归运行循环时(这就是执行该行时会发生的情况):

It is possible to run a run loop recursively. In other words, you can call CFRunLoopRun, CFRunLoopRunInMode, or any of the NSRunLoop methods for starting the run loop from within the handler routine of an input source or timer. When doing so, you can use any mode you want to run the nested run loop, including the mode in use by the outer run loop.

所以重点是做这样的事情:

- (NSMutableData *)serverRequest
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:url]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
[[NSURLConnection alloc]initWithRequest:request delegate:self];

CFRunLoopRun();
return _returnDataFromServer;
}

所以 serverRequest 方法不会退出,直到你真正停止 RunLoop:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_connectionData appendData:data];

CFRunLoopStop(CFRunLoopGetCurrent());
}

我不会这样做,最好将这部分工作传递给一个工作线程。还有其他方法可以实现相同的效果而不使用 Run Loop。

关于objective-c - iOS:CFRunLoopRun() 函数困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13548188/

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