ios - How to edit a UITableViewCell in a completion block from a method called inside the delegate method cellForRowAtIndexPath: -
in uitableview delegate method cellforrowatindexpath:(nsindexpath *)indexpath, want set image cell imageview. if image not available, download , set asynchronously in complete block. problem because cells reusable, maybe when completion block called, cell may not exist anymore. how can update cell when completion block called? or way ok?
- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { friendtableviewcell *cell = [self.tableview dequeuereusablecellwithidentifier:@"friend cell"]; friend *friend = self.friends[indexpath.row]; if (friend.picture) { cell.userprofileimageview.image = [uiimage imagewithdata:picturedata]; } else { cell.userprofileimageview.image = nil; nsurl *pictureurl = [nsurl urlwithstring:[nsstring stringwithformat:@"https://graph.facebook.com/%@/picture?type=normal&return_ssl_res", friend.facebookid]]; nsurlrequest *urlrequest = [nsurlrequest requestwithurl:pictureurl]; // run network request asynchronously [nsurlconnection sendasynchronousrequest:urlrequest queue:[nsoperationqueue mainqueue] completionhandler:^(nsurlresponse *response, nsdata *data, nserror *connectionerror) { if (connectionerror == nil && data != nil) { friend.picture = data; friendtableviewcell *celltoupdate = (friendtableviewcell *)[self.tableview cellforrowatindexpath:indexpath]; celltoupdate.userprofileimageview.image = [uiimage imagewithdata:data]; } }]; } return cell; }
in completion handler ask table reload affected row. data model has picture, update correctly. protects against cells being off screen result in noop(). when scroll picture in data model.
so like:
[nsurlconnection sendasynchronousrequest:urlrequest queue:[nsoperationqueue mainqueue] completionhandler:^(nsurlresponse *response, nsdata *data, nserror *connectionerror) { if (connectionerror == nil && data != nil) { friend.picture = data; self.tableview reloadrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationnone] } }];
if decide run asynchronous request in non main thread, need schedule row reload on main thread.
Comments
Post a Comment