我在NSBlockOperation中使用NSBlockOperation,我将这个操作添加到NSOperationQueue.But --不是working.When,我调用NSBlockOperation的start方法--那么它可以工作,但是当我将NSBlockOperation添加到NSOperationQueue时,它就不能工作了。
有人能帮我吗?
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount:1];
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLConnection *connection1 = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[connection1 start];
}];
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:@"http://urls.api.twitter.com/1/urls/count.json"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLConnection *connection2 = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[connection2 start];
}];
[operation2 addDependency:operation1];
[operationQueue addOperation:operation1];
[operationQueue addOperation:operation2];我还将NSURLConnectionDataDelegate实现为:
请帮忙谢谢
发布于 2014-04-11 14:47:50
我发现您的代码至少有两个问题:
- (void)start之后打电话给- (id)initWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate。它本身就开始了。- (id)initWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate是异步的,所以您必须在操作正常的同时保持操作正常,而您的operationQueue不应该是一个“堆栈”变量。如何轻松地修复它:
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error中使用blockOperations。它在执行加载时阻塞当前线程。示例:
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:@"http://urls.api.twitter.com/1/urls/count.json"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
}];还有很多其他的方法,但是第一种方法应该非常好。
发布于 2014-04-11 13:31:16
试着做:
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLConnection *connection1 = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[connection1 scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[connection1 start];
}];其原因是NSURLConnection试图在已启动的线程的run循环上传递它的委托更新,在您的例子中,它是另一个线程,它备份NSOperationQueue的队列,在网络调用返回时该线程可能已被回收,并且将没有运行循环来处理源,因此您不会命中您的委托。使用这种方法,您将在主运行循环中获得这些事件,该循环肯定是活动的。
使用NSURLConnection的方式是异步,而不是使用异步的sendSynchronousRequest:returningResponse:error:方式,后者是同步的。因此,在另一个线程中启动它是没有意义的。
但是,如果您只是尝试进行异步网络通信,则可以使用sendAsynchronousRequest:queue:completionHandler:方法来简化代码。这样您就不需要实现任何委托了。您可能会遇到的唯一问题是,如果存在某种身份验证,那么您将需要您所使用的方法。
https://stackoverflow.com/questions/23013479
复制相似问题