如何在NSOperation中执行异步NSURLConnection? [英] How do I do an Asynchronous NSURLConnection inside an NSOperation?

查看:123
本文介绍了如何在NSOperation中执行异步NSURLConnection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在后台线程的NSOperation内部进行Asynchrous NSURLConnection。

I want to do an Asynchrous NSURLConnection inside of an NSOperation on a background thread.

(这是因为我对数据进行了一些非常昂贵的操作他们回来了,希望在数据进入和后台时完成)

(it is because I'm doing some very expensive operations on the data as they come back that want to be done as the data comes in and in background)

这是我的第一次尝试:

在我的AppDelegate中:

IN my AppDelegate:

// create the opperation and add it to the queue:
self.sharedOperationQueue = [[[NSOperationQueue alloc] init] autorelease];
LibXMLOperation *op = [[[LibXMLOperation alloc] init] autorelease];
[self.sharedOperationQueue addOperation:op];

这是我的操作:

@interface EbirdLibXMLOperation : NSOperation {
@private
  NSURLConnection *urlConnection;
 // Overall state of the parser, used to exit the run loop.
 BOOL done;
 // properties to maintain the NSOperation
 BOOL finished;
 BOOL executing;  
}
- (void)downloadAndParse:(NSURL *)url;
- (void)start;
- (BOOL)isConcurrent;
- (BOOL)isFinished;
- (BOOL)isExecuting;

@property BOOL done;
@property (nonatomic, retain) NSURLConnection *ebirdConnection;
// The autorelease pool property is assign because autorelease pools cannot be retained.
@property (nonatomic, assign) NSAutoreleasePool *downloadAndParsePool;

@end


@implementation LibXMLOperation
@synthesize urlConnection, done;

- (void)start{
  if (![self isCancelled]) {
    [self willChangeValueForKey:@"isExecuting"];
    executing = YES;
    //set up the thread and kick it off...
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURL *url = [NSURL URLWithString:@"http://google.com"];
    [NSThread detachNewThreadSelector:@selector(downloadAndParse:) toTarget:self withObject:url];
    [self didChangeValueForKey:@"isExecuting"];
  } else {
    // If it's already been cancelled, mark the operation as finished.
    [self willChangeValueForKey:@"isFinished"];
    finished = YES;
    [self didChangeValueForKey:@"isFinished"];
  }
}

- (BOOL)isConcurrent {
  return YES;
}

- (BOOL)isExecuting {
  return executing;
}

- (BOOL)isFinished {
  return finished;
}


- (void)downloadAndParse:(NSURL *)url {
  self.downloadAndParsePool = [[NSAutoreleasePool alloc] init];
  done = NO;
  self.characterBuffer = [NSMutableData data];
  [[NSURLCache sharedURLCache] removeAllCachedResponses];
  NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];
  urlConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
  if (urlConnection != nil) {
    do {
      [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    } while (!done);
  }
  [self willChangeValueForKey:@"isFinished"];
  [self willChangeValueForKey:@"isExecuting"];
  finished = YES;
  executing = NO;
  // Clean up.
  self.urlConnection = nil;
  [downloadAndParsePool release];
  NSLog(@"download and parse cleaning up");
  self.downloadAndParsePool = nil;
  [self didChangeValueForKey:@"isExecuting"];
  [self didChangeValueForKey:@"isFinished"];  
}


#pragma mark NSURLConnection Delegate methods

// Disable caching so that each time we run this app we are starting with a clean slate.

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
  return nil;
}

// Forward errors to the delegate.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  done = YES;
}

// Called when a chunk of data has been downloaded.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  // Process the downloaded chunk of data.
  NSLog(@"Did received %i bytes", [data length]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  // Set the condition which ends the run loop.
  done = YES; 
}    

@end

当这个运行时,我看到我日志中的以下消息:

When this runs, I see the following message in my log:

2009-08-20 15:18:48.858 App[1001:3e03]*** _NSAutoreleaseNoPool(): Object 0x1126a20 of class NSCFArray autoreleased with no pool in place - just leaking
Stack: (0x305a2e6f 0x30504682 0x3057deba 0x305ced09 0x30577ddf 0x3056b43e 0x3050764a 0x58fc3 0x3050a79d 0x3050a338 0x94568155 0x94568012)

此事件发生在最后[self didChangeValueForKey:@isFinished];这告诉我,我正在设置NSOperation错误。

This event happens at the very last [self didChangeValueForKey:@"isFinished"]; which suggests to me that I'm setting up the NSOperation wrong.

推荐答案

移动线:

[downloadAndParsePool release];
self.downloadAndParsePool = nil;

-downloadAndParse结尾:方法。

这篇关于如何在NSOperation中执行异步NSURLConnection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆