Objective c iOS:CFRunLoopRun()函数混淆

Objective c iOS:CFRunLoopRun()函数混淆,objective-c,ios,multithreading,cfrunloop,Objective C,Ios,Multithreading,Cfrunloop,我读过关于CFRunLoop的文章,但仍然有点困惑。我来了一个十字架,一段我想为自己澄清的代码: NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:[NSString stringWithFormat:url]]]; [request setHTTPMethod:@"POST"]; [request setValue:@"applicati

我读过关于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()函数调用生成一个新线程


谢谢

假设这是从主线程调用的,实际上没有任何理由调用
CFRunLoopRun
,因为默认运行循环应该已经在运行


使用
NSURLConnection
的方式不会阻止调用线程。它可能会在内部产生额外的线程,但您实际上不必关心这一点
initWithRequest:delegate:
将立即返回,稍后将调用您的委托方法(当接收到响应、加载数据等时)。

实际上在某种情况下,它是有意义的。创建递归运行循环时(执行该行时会发生这种情况):

可以递归地运行run循环。换句话说,你可以 调用CFRunLoopRun、cfrunloopinmode或任何NSRunLoop方法 用于从输入的处理程序例程中启动运行循环 源或计时器。执行此操作时,您可以使用想要运行的任何模式 嵌套运行循环,包括外部运行循环使用的模式

所以关键是要这样做:

- (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
将不会退出,直到您实际停止运行循环:

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

    CFRunLoopStop(CFRunLoopGetCurrent());
}

我不会这样做,最好将这项工作传递给一个工作线程。还有其他方法可以实现同样的效果,而不使用运行循环。

很有趣。因此,在委托的ConnectiondFinishLoading中,我看到了以下调用:CFRunLoopStop(CFRunLoopGetCurrent());根据你的回答,这会引起任何问题吗?它会尝试停止默认的运行循环吗?我猜您正在查看的代码设计为在辅助线程上运行。根据我对
CFRunLoopRun
工作原理的理解,
CFRunLoopStop
应该只停止由
CFRunLoopRun
创建的嵌套运行循环,但我可能错了。在主线上,这两件事都没有多大意义。这是我的想法,但需要确认。谢谢。这通常是在后台线程中进行请求时运行的。