2010-07-11 65 views
0

我有一個將數據遠程加載到核心數據的ipad應用程序,我不斷向標籤顯示狀態更新,但看起來好像我的方法中的所有內容都必須在消息發送到UILabel之前完成。在ipad應用中向用戶顯示實時信息?

我該如何解決這個問題?

示例代碼:

-(void) importCollections { 
/* code left out for brevity */ 

    for (int j=0; j <[[myCollections objectAtIndex:i] count]; j++) 
      { 

       Collection *entity = (Collection*) [NSEntityDescription insertNewObjectForEntityForName:@"Collection" inManagedObjectContext:managedObjectContext]; 
       [entity setCollectionName:[[[myCollections objectAtIndex:i] objectAtIndex:j] valueForKey:@"CollectionName"]]; 
       [entity setCollectionID:[[[myCollections objectAtIndex:i] objectAtIndex:j] valueForKey:@"CollectionID"]]; 
       [entity setManufacturer:[manufacturers objectAtIndex:i]]; 

       NSError *error; 

       if (![managedObjectContext save:&error]) { 
        // Handle the error. 
        NSLog(@"%@",error); 
       } 
       importStatus.text =[NSString stringWithFormat:@"importing collection: %@", entity.CollectionName]; 
      } 
} 

在importStatus上面的代碼是我需要不斷更新的UILabel,但似乎要等到這個方法的一切完成之後。

回答

1

您可能會從主線程調用importCollections。這樣,只要您阻止主線程並且不返回運行循環,您就不會給UIKit更新UI的機會。

您應該在後臺線程上執行冗長的計算或加載資源。由於您只能從主線程更新UI元素,因此您必須將UIKit調用包裝到performSelectorOnMainThread:withObject:waitUntilDone:中。

+0

是有意義的,所以我關閉了所有在後臺線程上的導入,並且能夠將消息發送到主線程上的UILabel,並讓用戶瞭解 - 我是否正確理解? – Slee 2010-07-11 12:29:15

+0

@Max Fraser:確實如此。所有花費比幾毫秒更長的時間應該在後臺線程上完成。由於運行循環體系結構和NSObject的performSelectorOnThread ... API,Cocoa中的線程通信很容易。 – 2010-07-11 13:58:25

相關問題