iphone网络多线程

时间:2011-09-20 08:28:07

标签: iphone

我有一个用于从网络接收数据的类,名为NetWorkConnect。以下方法在NetWorkConnect.m中,这是委托方法。 m_DisplayMarketViewController是类DisplayMarketViewController的实例。

-(void)stream:(NSStream*)stream handleEvent:(NSStreamEvent)eventCode{
    switch (eventCode) {
        case NSStreamEventHasBytesAvailable:
        {
            if (data == nil) {
            data = [[NSMutableData alloc] init];
            }
            uint8_t buf[1024];
            unsigned int len = 0;
            len = [(NSInputStream *)stream read:buf maxLength:1024];
            if(len) {    
            [data appendBytes:(const void *)buf length:len];
            } else {
            NSLog(@"No data.");
            }  
           [self storeData:data];              
           [m_DisplayMarketViewController updateMarket:self];                   
    } break;  
    default:
      break;
    }
}

方法updateMarket将self传递给DisplayMarketViewController,因此DisplayMarketViewController可以使用从网络接收的数据。在DisplayMarketViewController.m文件中将显示数据。但是当我更新数据时,我可以显示数据,但是inteface似乎有点受阻,所以我打算使用multiThreading ......但是怎么做呢?谢谢。

1 个答案:

答案 0 :(得分:0)

You can subclassing  NSOperation and in implementation file you can try something like this.

- (void)main 
{
    @try 
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

        executing_ = YES;
       [self performSelector:@selector(makeSomethingInBackground:) onThread:[NSThread      currentThread] withObject:nil waitUntilDone:NO];
[pool drain];
    }
    @catch (NSException * e)  {
        NSLog(@"Exception: %@", e);
    }
}


#pragma mark -
#pragma mark Overrides

- (BOOL)isConcurrent
{
    return YES;
}

- (BOOL)isExecuting
{
    return executing_;
}

- (BOOL)isFinished
{
    return finished_;
}

- (void)cancel
{
    [super cancel];
    [self done];
}
In another class create instance of your NSOperation subclass.
YourNSOperationSubclass *operation = [YourNSOperationSubclass new];
NSOperationQueue *op = [NSOperationQueue new];  [op addOperation operation];