【问题标题】:Checking for NSRunLoop and using appropriate NSURLConnection method检查 NSRunLoop 并使用适当的 NSURLConnection 方法
【发布时间】:2012-04-12 01:41:18
【问题描述】:

我正在做一个个人项目,昨晚遇到了 NSURLConnection 的异步特性。我正在构建一个与 restful api 接口的库。我期待在 Foundation 命令行工具和 Cocoa 应用程序中重用这个库。

有没有一种方法可以检查 runloop 是否可用于调用同步方法,如果是,则发送同步请求(如果在命令行工具中使用)。

或者,有没有办法始终使用异步方法,但强制应用程序在异步请求完成之前不退出?

我注意到this,但我宁愿不必将调用放在库外运行。

感谢您的帮助

【问题讨论】:

    标签: objective-c cocoa foundation


    【解决方案1】:

    或者,有没有办法始终使用异步方法,但强制应用程序在异步请求完成之前不退出?

    如鱼得水:

    int main(int argc, char *argv[])
    {   
        // Create request, delegate object, etc.
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request 
                                                                      delegate:delegate 
                                                              startImmediately:YES];
        CFRunLoopRun();
        // ...
    }
    

    我在这里使用CFRunLoopRun() 是因为以后可以在代理确定连接完成时停止它:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        // This returns control to wherever you called
        // CFRunLoopRun() from.
        CFRunLoopStop(CFRunLoopGetCurrent());
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        NSLog(@"Error: %@", error);
        CFRunLoopStop(CFRunLoopGetCurrent());
    }
    

    另一种选择是在 while 循环中使用 -[NSRunLoop runUntilDate:],并让委托设置“停止”标志:

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request 
                                                                  delegate:delegate 
                                                          startImmediately:YES];
    
    while( ![delegate connectionHasFinished] ){
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1];
    }
    

    【讨论】:

      【解决方案2】:

      我想您可以通过查看NSClassFromString(@"NSApplication") 是否返回非Nil 来检查程序是否链接到 AppKit。然后,您可以使用+[NSThread isMainThread] 检查您是否在主线程上。

      但是,图书馆试图“强制”应用程序不以任何原因退出是糟糕的设计。只需确定该库需要应用程序的合作,并提供一个清理和完成例程供其调用。可能还有一个正在进行的事情吗?功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-13
        • 1970-01-01
        • 2011-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多