How do I start an Asynchronous NSURLConnection inside an NSOperation?

前端 未结 3 593
南笙
南笙 2021-01-06 06:27

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

3条回答
  •  耶瑟儿~
    2021-01-06 07:05

    -(void)start
    {
      [self willChangeValueForKey:@"isExecuting"];
      _isExecuting = YES;
      [self didChangeValueForKey:@"isExecuting"];
      NSURL* url = [[NSURL alloc] initWithString:@"http://url.to/feed.xml"];
      NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
      _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; // ivar
      [request release];
      [url release];
      // Here is the trick
      NSPort* port = [NSPort port];
      NSRunLoop* rl = [NSRunLoop currentRunLoop]; // Get the runloop
      [rl addPort:port forMode:NSDefaultRunLoopMode];
      [_connection scheduleInRunLoop:rl forMode:NSDefaultRunLoopMode];
      [_connection start];
      [rl run];
    }
    

    More details can be found here: link

提交回复
热议问题