2012-01-31 43 views
1

OK。我不完全清楚塊,但我經常使用它們;尤其是在執行ASIHTTPRequest時。我想傳遞一個對象到塊中,並在請求完成時爲該對象分配一個值,但我不知道如何在塊內使對象「可用」。將對象傳入ASIHTTPRequest塊

這裏是我的方法......

- (void)fetchImageAsynchronously:(NSURL *)theURL intoImageObject:(UIImage *)anImageObject 
{ 
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theURL]; 
    [request setDownloadCache:[ASIDownloadCache sharedCache]]; 
    [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy]; 
    [request setCompletionBlock:^{ 
     NSData *responseData = [request responseData]; 
     anImageObject = [UIImage imageWithData:responseData]; 
    }]; 
    [request setFailedBlock:^{ 
     // NSError *error = [request error]; 
    }]; 
    [request startAsynchronous]; 
} 

因此,請求完成時,我想anImageObject的價值是獲取圖像。但anImageObject在塊內不可用。

有人會好心幫忙嗎?

回答

1

anImageObject將不得不通過引用傳遞。也就是UIImage **,並在調用方法時傳遞anImageObject的地址。

這不是一個很好的設計,因爲你還必須管理一個圖像對象的生命週期,並且可能會發布一些準備就緒的通知。也就是說,如果在下載圖像數據所需的時間內解除分配一個圖像對象,則該代碼將會中斷。你不會知道一個圖像對象是用數據初始化還是不是。

- (void)fetchImageAsynchronously:(NSURL *)theURL intoImageObject:(UIImage **)anImageObject 
{ 
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theURL]; 
    [request setDownloadCache:[ASIDownloadCache sharedCache]]; 
    [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy]; 
    [request setCompletionBlock:^{ 
     NSData *responseData = [request responseData]; 
     *anImageObject = [UIImage imageWithData:responseData]; 
    }]; 
    [request setFailedBlock:^{ 
     // NSError *error = [request error]; 
    }]; 
    [request startAsynchronous]; 
}