ios - 使用 NSNotification defaultCenter 响应缓慢

标签 ios performance uitableview uibutton nsnotificationcenter

您好,我正在使用 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/

相关文章:

ios - 如何限制只对某些用户删除 TableView 中的行?

ios - 如何从 UITableView 单元格中获取 id 完整数组值?

ios - 自定义开放图谱故事未通过 Facebook 审核

django - 配置 uwsgi 服务器以提高性能

iphone - 在 iPhone 5 上使用 EGOPhotoViewController

mysql - 性能问题(Nginx、NodeJs、Mysql)

java - 完成一个功能;返回无效或中断循环?

ios - UITableView 中不可见的标签文本

ios - 文字转语音 : highlighting word by word for iphone

ios - 在Objective-C中设置另一个类的属性