您好,我正在使用 NSNotificationCenter defaultCenter 在我的应用中实现“赞”和“评论”功能。
//In Answer Table View
@implementation AnswerTableView
- (id)initWithParentController:(UIViewController *)pController andResourcePath:(NSString *)thisResourcePath {
....
// Notification to reload table when a comment is submitted
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reloadTable)
name:@"Comment Submitted"
object:nil];
// Notification to reload table when an answer is liked
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reloadTable)
name:@"Answer Liked"
object:nil];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
//In custom button implementation - THIS BUTTON IS CREATED IN EVERY CELL OF THE TABLEVIEW
@implementation UICustomButton
-(id)initWithButtonType:(NSString *)type {
self = [super init];
if (self) {
//Initialization done here
}
return self;
}
- (void)buttonPressed {
if ([btnType isEqualToString:@"like"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"Answer Liked" object:nil];
}
else if ([btnType isEqualToString:@"comment"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"Comment Submitted" object:nil];
}
}
但是,我发现在使用这些函数一段时间后,table reload的响应速度越来越慢(到了崩溃的地步)。
我是否遗漏了实现中的任何内容,即释放等
最佳答案
您重复添加观察者并且速度变慢是因为通知代码必须循环遍历越来越多的观察者以发送通知。您可能正在崩溃,因为您泄露了太多此类 View 。
在您的 dealloc 中放置一条日志语句,以查看这些实例是否曾经被清理过。 dealloc 方法中的 removeObserver 也可能存在计时问题。如果可以,请尝试在 dealloc 之前删除观察者。
关于ios - 使用 NSNotification defaultCenter 响应缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11705252/