下面是我最终编写的使用NSNotificationCenter和UITableView获取积分的代码。也许它会帮助别人。
在收藏类:
+ (void)toggleFavorite:(NSString *)artistName {
if([favorites member:artistName]) {
[favorites removeObject:artistName];
[[NSNotificationCenter defaultCenter] postNotificationName:@"favoriteRemoved"
object:artistName];
} else {
[favorites addObject:artistName];
[[NSNotificationCenter defaultCenter] postNotificationName:@"favoriteAdded"
object:artistName];
}
[[UserLibrary current] verifyLibrary];
}
之一,与收藏互动的3次:表视图,其中每个单元都有一个明星:
// register for notifications
- (void)awakeFromNib {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(favoriteAdded:)
name:@"favoriteAdded"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(favoriteRemoved:)
name:@"favoriteRemoved"
object:nil];
}
// search through visible cells for the one that needs to be starred
- (void)favoriteAdded:(NSNotification *)notification {
NSString *artistName = notification.object;
for(ArtistTableViewCell *cell in [(UITableView*)self.view visibleCells]) {
if([artistName isEqualToString:cell.artistLabel.text]) {
cell.starred = YES;
}
}
}
// search through visible cells for the one that needs to be de-starred
- (void)favoriteRemoved:(NSNotification *)notification {
NSString *artistName = notification.object;
for(ArtistTableViewCell *cell in [(UITableView*)self.view visibleCells]) {
if([artistName isEqualToString:cell.artistLabel.text]) {
cell.starred = NO;
}
}
}
// when cells are created or reused, make sure the star is set properly
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ArtistTableViewCell *cell = ...
NSString *name = ...
cell.starred = [Favorites isFavorite:name];
return cell;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
表格的单元格。请注意,单元格是如何从TableView接收事件的,因此它们不必注册通知(并在离队后有被通知的风险)。
- (IBAction)starPressed:(id)sender {
NSString *name = artistLabel.text;
[Favorites toggleFavorite:name];
}
- (void)setStarred:(bool)isFavorite {
UIImage *img;
if(isFavorite) {
img = [UIImage imageNamed:@"filledstar30px"];
} else {
img = [UIImage imageNamed:@"emptystar30px"];
}
[favoriteButton setImage:img forState:UIControlStateNormal];
}