下面是我最終編寫的使用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];
}