我想在后台线程的NSOperation内部做一个Asynchrous NSURLConnection。这是因为我们在数据回复时正在对数据进行一些非常昂贵的操作。如何在NSOperation内启动异步NSURLConnection?
这是一个非常类似的问题他们问什么位置: How do I do an Asychronous NSURLConnection inside an NSOperation?
,但不同的是,我运行另一个类的连接。
这是我第一次尝试:
在我MainViewController:
@property (nonatomic, strong) NSOperationQueue *requestQueue;
#pragma mark - Lazy initialization
- (NSOperationQueue *)requestQueue
{
if (!_requestQueue) {
_requestQueue = [[NSOperationQueue alloc] init];
_requestQueue.name = @"Request Start Application Queue";
_requestQueue.maxConcurrentOperationCount = 1;
}
return _requestQueue;
}
-(void)callToServer
{
URLJsonRequest *request = [URLRequestFactory createRequest:REQUEST_INTERFACE_CLIENT_VERSION
delegate:self];
RequestSender *requestSender = [[RequestSender alloc]initWithPhotoRecord:request delegate:self];
[self.requestQueue addOperation:requestSender];
}
这里是我的操作:
- (id)initWithPhotoRecord:(URLJsonRequest *)request
delegate:(id<RequestSenderDelegate>) theDelegate{
if (self = [super init])
{
self.delegate = theDelegate;
self.jsonRequest = request;
}
return self;
}
- (void)main {
//Apple recommends using @autoreleasepool block instead of alloc and init NSAutoreleasePool, because blocks are more efficient. You might use NSAuoreleasePool instead and that would be fine.
@autoreleasepool
{
if (self.isCancelled)
return;
[self.jsonRequest start];
}
}
这里是我的请求启动功能:
-(void) start
{
NSURL *url = [NSURL URLWithString:@"http://google.com"];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];
urlConnection = [[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]autorelease];
[urlConnection start];
[theRequest release]
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"Received reponse from connection");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
}
我没有收到服务器的回应。 感谢
顺便说一句,如果你使用'initWithRequest'没有设置为'NO'了'startImmediately'选项,你不应该',否则自动start'连接(因为它会开始,并发出另一个'开始'会干扰)。考虑到你需要在运行循环中安排它,使用'startImmediately'设置为'NO'的方式,在运行循环中调度它,然后'开始'它。 – Rob
也许我忽略了一些东西,但是我也没有看到你为[isExecuting]和'isFinished'做了必要的KVN通知,当[子类化你自己的操作](http:// developer。 apple.com/library/mac/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationObjects/OperationObjects.html#//apple_ref/doc/uid/TP40008091-CH101-SW16)。还是你不支持并发操作? – Rob
如果要控制同时活动连接的最大数量,则只需要'NSOperation'的子类。否则,从NSOperation继承子是毫无意义的。无论如何,'NSURLConnection'不会在队列的执行上下文中运行 - 除了start方法。什么是重要的是你的委托方法将被执行。使用专用线程是一种方法,将工作(处理块)分派到另一个队列是另一种方法。两种方法都有优点和缺点。 – CouchDeveloper