2011-04-12 30 views
0

我使用NSOperationQueue加載UIImageView。UIImageView問題通過OperationQueue加載

負載從Internet獲取圖像,然後將其添加到圖像視圖。我的問題是,該方法結束,但它需要約3秒後的圖像視圖實際上任一顯示圖像,或從上海華移除圖像視圖...

- (void)viewDidLoad { NSLog(@"AirportDetailView: viewDidLoad"); 
    [super viewDidLoad]; 
    [self.activity startAnimating]; 
    self.queue = [NSOperationQueue new]; 
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImage) object:NULL]; 
    [self.queue addOperation:operation]; 
    [operation release]; 
} 

-(void)loadImage { 
     [myAp ImageForAp]; 

     NSLog(@"ImageFor Ap Ended, %@",myAp.ApDiagram); 

     [self.activity stopAnimating]; 

     if (myAp.ApDiagram==NULL) { 
      NSLog(@"Finally Gets Here"); 
      [self.Diagram removeFromSuperview]; 
     } 
     else { 
      NSLog(@"Finally Gets Here with Diag"); 
      [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal]; 
     } 

    } 

所述的NSLog顯示之間的延遲約3秒前兩個日誌語句不明白爲什麼....

更新了我的最新的代碼......

-(void)loadImage { 

    [myAp ImageForAp]; 

    NSLog(@"ImageFor Ap Ended, %@",myAp.ApDiagram); 

    [self performSelectorOnMainThread:@selector(UpdateUI) withObject:nil waitUntilDone:NO]; 
} 

-(void)UpdateUI { 

    [self.activity stopAnimating]; 

    if (myAp.ApDiagram==NULL) { 
     NSLog(@"Finally Gets Here"); 
     [self.Diagram removeFromSuperview]; 
    } 
    else { 
     NSLog(@"Finally Gets Here with Diag"); 
     [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal]; 
    } 
} 

回答

1

確保loadImage方法正在運行主線程。所有UI操作都需要在主線程上按預期工作。您的代碼需要與此類似。

-(void)loadImage { 
    [myAp ImageForAp]; 
    [self performSelectorOnMainThread:@selector(UpdateUI) withObject:nil waitUntilDone:NO]; 
} 

-(void)UpdateUI { 
    [self.activity stopAnimating]; 

    if (myAp.ApDiagram==NULL) { 
     [self.Diagram removeFromSuperview]; 
    } 
    else { 
     [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal]; 
    } 
} 

viewDidLoad中還有可能的內存泄漏。

self.queue = [NSOperationQueue new];應改爲

self.queue = [[[NSOperationQueue alloc] init] autorelease];

+0

好,我把它關閉主線程,當我使用NS操作隊列的問題是,當我加載視圖會拖延在應用程序加載它加載視圖之前的導航步驟 – 2011-04-12 20:02:41

+0

- (void)viewDidLoad NSLog(@「AirportDetailView:viewDidLoad」); \t [super viewDidLoad]; \t \t \t [self.activity startAnimating]; \t self.queue = [NSOperationQueue new]; \t \t * NSInvocationOperation操作= [[NSInvocationOperation的alloc] initWithTarget:自 \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t選擇器:@selector(的LoadImage) \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t對象:NULL]; \t [self.queue addOperation:operation]; \t [操作發佈]; – 2011-04-12 20:05:30

+0

你想要在後臺完成所有的圖像下載(你的NSOperation),但是你的控制UI的代碼只需要移動到主線程,比如[self.activity stopAnimating];該代碼中也存在錯誤。編輯您的原始文章和該代碼示例,我將能夠更新我的答案。 – Joe 2011-04-12 20:06:54