簡體   English   中英

如何等待findObjectsInBackgroundWithBlock(在Parse中)完成,然后運行MainThread?

[英]How to wait for findObjectsInBackgroundWithBlock (in Parse) finish then run the MainThread?

我正在使用解析來存儲我的數據。 在我的AppDelegate中,我想從服務器獲取所有數據,然后將它們共享到ViewController,但是我做不到。 因為我的MainThread總是在收集數據線程之前完成。 有什么方法可以首先獲取所有數據,或者等待數據線程完成然后再執行Mainthread,或者采用另一種方法來實現此目的。

這是我的代碼:

@synthesize authors;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [SCategory registerSubclass];
    [Parse setApplicationId:PARSE_APP_ID clientKey:PARSE_CLIENT_KEY];

     PFQuery *query = [SCategory query];

    // type =1 : programmes
   [query whereKey:@"type" equalTo:@1];
   [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {

            // The find succeeded.
            authors = [[NSMutableArray alloc] initWithArray:objects];
            NSLog(@"inside block author: %d",[authors count]);
       } else {
            // Log details of the failure
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];



   NSLog(@"outside block author: %d",[authors count]);

        return YES;
    }

我的輸出

2013-11-15 15:00:59.424 Sala[5340:70b] outside block author: 0
2013-11-15 15:01:00.804 Sala[5340:70b] inside block author: 4

我希望我的“外部區塊作者= 4”,但>。<

您不希望或嘗試阻塞主線程。 該塊的全部要點是它是一個異步過程,您應該對其進行處理。

正確的方法是:

在應用程序委托中獲取數據,然后在成功塊中獲取視圖控制器並將其傳遞給數據。

要么:

將邏輯移至視圖控制器,以便在顯示邏輯時決定是否需要獲取數據,並管理下載,然后更新其UI。

我想出了什么解決方案,所以我決定不使用findObjectsInBackgroundWithBlock而是僅使用findobject,因此此方法將同步運行。 authors = [query findObjects];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM