2011-03-24 37 views
0

我在應用程序中有一個HUD面板,我希望能夠在顯示下一個圖像之前拍攝一組圖像並在面板上顯示每個圖像幾秒鐘。我對Cocoa很陌生,並且在實現時遇到了麻煩,所以有些指針會受到歡迎。下面是我目前想:可可圖片庫窗口

[newShots enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) 
{ 
    //get url 
    NSURL *imageUrl = [[NSURL alloc] initWithString:[obj objectForKey:@"image_url"]];; 

    //get image from url 
    NSImage *image = [[NSImage alloc] initWithContentsOfURL:imageUrl]; 

    //set it to shot panel 
    [shotPanelImageView setImage:image]; 

    //clean up 
    [imageUrl release]; 
    [image release]; 

    //set needs refresh 
    [shotPanelImageView setNeedsDisplay:YES]; 

    //sleep a few before moving to next 
    [NSThread sleepForTimeInterval:3.0]; 
}]; 

正如你看到的,我只是循環的每個圖像的信息,通過URL抓住它,將其設置爲視圖,然後調用幾秒鐘線程睡眠繼續前進。問題是視圖在分配時不會與新圖像一起重繪。我認爲setNeedsDisplay:YES會強制重繪,但只會顯示集合中的第一個圖像。我已經放入了NSLog()並進行了調試,我確信枚舉工作正常,因爲我可以看到應該設置的新圖像信息。

有什麼我失蹤或是這是一個完全錯誤的方式去解決這個問題?

感謝,

克雷格

回答

1

你都睡在主線程,我敢肯定不是一個好主意。我建議Cocoa做你想做的事情就是使用計時器。代替你的代碼上面的:

[NSTimer scheduledTimerWithTimeInterval:3.0 
           target:self 
           selector:@selector(showNextShot:) 
           userInfo:nil 
           repeats:YES]; 

(該userInfo參數可以讓你沿着你想要當定時器觸發使用任意物體通過,所以你可能會使用它來跟蹤當前指數作爲一個NSNumber,但它必須包裝在一個可變容器對象中,因爲以後不能設置它。)

然後將塊中的代碼放入由計時器調用的方法中。您需要爲當前索引創建一個實例變量。

- (void)showNextShot:(NSTimer *)timer { 
    if(currentShotIdx >= [newShots count]){ 
     [timer invalidate]; // Stop the timer 
     return; // Also call another cleanup method if needed 
    } 
    NSDictionary * obj = [newShots objectAtIndex:currentShotIdx]; 
    // Your code... 
    currentShotIdx++; 
} 

爲避免因使用計時器最初的3秒延遲,你可以打電話給你的計時器使用相同的方法,你將它設置權之前:

[self showNextShot:nil] 
[NSTimer scheduled... 

或者也可以安排一個非 - 重複計時器,以儘快解僱(如果你真的想使用userInfo):

[NSTimer scheduledTimerWithTimeInterval:0.0 
             ... 
           repeats:NO]; 

編輯:我忘了-initWithFireDate:interval:target:selector:userInfo:repeats:

NSTimer *tim = [[NSTimer alloc] initWithFireDate:[NSDate date] 
             interval:3.0 
              target:self 
             selector:@selector(showNextShot:) 
             userInfo:nil 
             repeats:YES]; 
[[NSRunLoop currentRunLoop] addTimer:tim 
          forMode:NSDefaultRunLoopMode]; 
[tim release];