作为 Doug 回应的推论,我最终得出的结论是:
每个file 都有一个唯一标识符,所以我让它负责发布有关其属性更新的通知(想想 KVO,但没有麻烦):
我创建了一个FileNotificationType 枚举(即FileNotificationTypeDownloadTriggered 和FileNotificationTypeDownloadProgress)。然后我会将进度与FileNotificationType 一起发送到NSNotification 的userInfo NSDictionary。
- (void)postNotificationWithType:(FileNotificationType)type andAttributes:(NSDictionary *)attributes
{
NSString *unique_notification_id = <FILE UNIQUE ID>;
NSMutableDictionary *mutable_attributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
[mutable_attributes setObject:@(type) forKey:@"type"];
NSDictionary *user_info = [NSDictionary dictionaryWithDictionary:mutable_attributes];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:unique_notification_id object:nil userInfo:user_info];
});
}
file 对象还有一个方法可以枚举它可以发送哪些类型的通知:
- (NSArray *)notificationIdentifiers
{
NSString *progress_id = <FILE UNIQUE ID + FILENOTIFICATIONTYPE>;
NSString *status_id = <FILE UNIQUE ID + FILENOTIFICATIONTYPE>
NSString *triggered_id = <FILE UNIQUE ID + FILENOTIFICATIONTYPE>
NSArray *identifiers = @[progress_id, status_id, triggered_id];
return identifiers;
}
因此,当您在别处更新 file 的属性时,只需执行以下操作:
NSDictionary *attributes = @{@"download_progress" : @(<PROGRESS_INTEGER>)};
[file_instance postNotificationWithType:FileNotificationTypeDownloadProgress andAttributes:attributes];
在接收端,我的表视图委托实现了这些方法来添加/删除我的自定义 UITableViewCells 作为这些通知的观察者:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
File *file = [modelObject getFileAtIndex:indexPath.row];
for (NSString *notification_id in file.notificationIdentifiers)
{
[[NSNotificationCenter defaultCenter] addObserver:cell selector:@selector(receiveFileNotification:) name:notification_id object:nil];
}
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
[[NSNotificationCenter defaultCenter] removeObserver:cell];
}
最后,自定义的UITableViewCell 必须实现receiveFileNotification: 方法:
- (void)receiveFileNotification:(NSNotification *)notification
{
FileNotificationType type = (FileNotificationType)[notification.userInfo[@"type"] integerValue];
// Access updated property info with: [notification.userInfo valueForKey:@"<Your key here>"]
switch (type)
{
case FileNotificationTypeDownloadProgress:
{
// Do something with the progress
break;
}
case FileNotificationTypeDownloadStatus:
{
// Do something with the status
break;
}
case FSEpisodeNotificationTypeDownloadTriggered:
{
// Do something if the download is triggered
break;
}
default:
break;
}
}
希望这可以帮助那些希望更新表格视图单元格而无需重新加载它们的人!比键值观察的好处是,如果 File 对象在单元格仍在观察的情况下被释放,您将不会遇到问题。我也不必打电话给cellForRow...。
享受吧!