- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在做一个个人项目,昨晚遇到了 NSURLConnection 的异步特性。我正在构建一个将与 restful api 接口(interface)的库。我期待在 Foundation 命令行工具和 Cocoa 应用程序中重用这个库。
有没有一种方法可以检查 runloop 是否可用于调用同步方法,如果是,则发送同步请求(如果在命令行工具中使用)。
或者,有没有办法始终使用异步方法,但强制应用程序在异步请求完成之前不退出?
我注意到了 this但我宁愿不必调用在图书馆外运行。
感谢您的帮助
最佳答案
Alternately, is there a way to always use the asynchronous method but force the application to not exit until the async request has finished?
简单易行:
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:]
,并让委托(delegate)设置一个“停止”标志:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:delegate
startImmediately:YES];
while( ![delegate connectionHasFinished] ){
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1];
}
关于objective-c - 检查 NSRunLoop 并使用适当的 NSURLConnection 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10106566/
这段代码在 Java 中的等价物是什么?我放了一部分,我对 I/O 部分感兴趣: int fd = open(FILE_NAME, O_WRONLY); int ret = 0; if (fd =
我正在尝试将维度为 d1,d2,d3 的张量 M[a1,a2,a3] reshape 为维度为 d2, d1*d3 的矩阵 M[a2,a1*a3]。我试过 M.reshape(d2,d1*d3) 但是
我是一名优秀的程序员,十分优秀!