2014-03-27 16 views
0

剛開始使用RAC,我想知道如何在TableView中的單元格中異步加載圖像。 我正在嘗試在文檔中的示例,但說實話,我不太明白... 事情是,該項目是與RAC編寫的,所以我想做正確的事情。iOS使用RAC在UITableViewCell中加載圖像

我有什麼企圖?:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"tableCell"; 
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
    cell.elementName.text = self.myListOfElements[indexPath.row].elementName; 
    RAC(cell.imageView, image) = [[finalImage map:^(NSURL *url) { 
            return [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.myListOfElements[indexPath.row].url]]]; 
            }] deliverOn:RACScheduler.mainThreadScheduler]; 
} 

但是,這是不工作... 是否有人知道正確的方式與RAC做到這一點?

回答

0

我從來沒有使用過RAC,但是基於這些例子,它看起來像是引用了一個你似乎沒有的URL。

RAC(self.imageView, image) = 
[ 
    [ 
     [ 
      [ 
       client fetchUserWithUsername:@"joshaber" 
      ] 
      deliverOn:[RACScheduler scheduler] 
     ] 
     map:^(User *user) { 
      // Download the avatar (this is done on a background queue). 
      return [[NSImage alloc] initWithContentsOfURL:user.avatarURL]; 
     } 
    ] 
    // Now the assignment will be done on the main thread. 
    deliverOn:RACScheduler.mainThreadScheduler 
]; 

在該示例本節:

[ 
    [ 
     client fetchUserWithUsername:@"joshaber" 
    ] 
    deliverOn:[RACScheduler scheduler] 
] 

-fetchUserWithUsername是返回包含用於下載圖像的URL的用戶對象的功能。

+0

不完全是答案,但感謝「顯示燈光」:) 在代碼中,您寫道,客戶端應該是一個信號,返回一個對象與您的數據。 –

0

此行假定已經有創建並設置在CustomTableViewCell的imageView屬性的UIImageView對象:這大概的UIImageView對象在CustomTableViewCell類的初始化或-prepareForReuse方法創建

RAC(cell.imageView, image) = [[finalImage map:^(NSURL *url) { 

。如果不是,那可能是你問題的一部分。

但請注意,此代碼看起來並不安全。如果CustomTableViewCell實例重新使用,那麼您可能會再次在對象上調用RAC(cell.imageView, image),這會是一個問題。 (另一方面,如果-prepareForReuse是每次創建一個新的UIImageView,那麼這應該不成問題。)