一个班级(管理一个列表)传播通知的好方法是什么?
问题描述:
我正在研究iPad应用程序,有许多页面供用户浏览。我正在为用户实现功能,以便“收藏”页面,以便稍后再访问它。一个班级(管理一个列表)传播通知的好方法是什么?
我在写一个收藏夹类,它将管理用户喜欢的页面列表。当用户按下'收藏夹'按钮时,它将调用收藏夹类中的addFavorite:或removeFavorite:方法。输入看起来很简单。
我的问题是:将状态改变事件传播到所有视图的最佳方式是什么?我在应用程序中散布了许多多余的“最喜爱的”指标,并且它们都需要保持同步。例如,如果用户在一个视图中最喜欢Pink Floyd(将星形从灰色更改为黄色),则链接到Pink Floyd的所有其他视图都需要在链接旁边显示黄色星星,而不是灰色星星。
这是我的理解,有很多方法来使用Objective-C通知来做到这一点。我只是在寻找一个清洁和可维护的。过去为你工作的是什么?谢谢你的时间。
答
检查NSNotificationCenter
和NSNotification
。我经常使用通知,特别是如果有多方对共享信息感兴趣使代表模式变得困难。我遇到的通知的主要问题是订阅UITableViewCell的通知:避免出列的单元格响应通知。
答
下面是我最终编写的使用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];
}