簡體   English   中英

在塊中使用調度異步

[英]Using Dispatch Async in Block

例如,當我使用塊時,最好在主線程上使用dispatch_async調用UI更新:

    PFFile *image = (PFFile *)[currentUser objectForKey:@"image"];
    [image getDataInBackgroundWithBlock:^(NSData *data, NSError *error){
        if (error)
        {
            self.profileImage.image = [UIImage imageNamed:@"image"];

        }
        else
        {
            UIImage *userImage = [UIImage imageWithData:data];
            self.profileImage.image = userImage;
        }
    }];

如果我輸入“ self.profileImage.image = userImage;”會更好嗎? 在其他條件下的分派異步中還是因為它是塊而被稱為異步,這是否重要?

如果設置self.profileImage.image導致用戶希望用戶立即更改UI,則應在主隊列上設置該屬性。 如果您只是設置與UI不直接相關的內部數據,則可以繼續在后台隊列上執行它。 因此,如果您想更新主隊列上的個人資料圖片,則可以使用

dispatch_async(dispatch_get_main_queue(), ^(void){
    self.profileImage.image = [UIImage imageWithData:data];
}

您需要在主線程中執行圖像加載操作。

self.profileImage.image = userImage;

上面的行是UI操作,就像在一個塊中一樣,這將花費一些時間來加載並使UI交互停止一段時間。

您只需要在主線程中調用此行:

PFFile *image = (PFFile *)[currentUser objectForKey:@"image"];
[image getDataInBackgroundWithBlock:^(NSData *data, NSError *error){
    if (error)
    {
        self.profileImage.image = [UIImage imageNamed:@"image"];

    }
    else
    {
        [self performSelectorOnMainThread:@selector(loadImage:) withObject:data waitUntilDone:YES];

    }
}];


- (void) loadImage:(NSData *)data {
            UIImage *userImage = [UIImage imageWithData:data];
            self.profileImage.image = userImage;
}

暫無
暫無

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

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