如何在NSMutableArray上添加观察者? [英] How to add observer on NSMutableArray?

查看:95
本文介绍了如何在NSMutableArray上添加观察者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了很多,但没有找到有用的代码或教程。



在我的应用程序中,我有一个可变数组,每60秒更新一次。 / p>

数组中的对象由多个视图控制器中的表视图显示。



我想重新加载表视图仅当数组中的值更改或更新时自动执行。



为此,我想在可变数组上添加观察者,即当数组中的值发生更改时,它应调用特定方法例如

   - (void)ArrayUpdatedNotification:(NSMutableArray *)array 
{
//重新加载表或做某事
}

提前致谢。

解决方案

可以做的是 - 更新阵列后发送通知(NSNotificationCenter),所有控制器都会收到此通知。收到通知后,控制器应该[tableview reloaddata]。



代码示例

  //添加观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTable :) name:@arrayUpdatedobject:nil];

//发布通知
[[NSNotificationCenter defaultCenter] postNotificationName:@arrayUpdatedobject:nil];

// void函数,在Notification addObserver方法定义的同一个类中指定
- (void)updateTable:(NSNotification *)note {
[tableView reloadData] ;
}


I have searched a lot but didn't find useful code or tutorial.

In my application, I have an mutable array which update in every 60 seconds.

The objects in array is being displayed by table view in multiple view controllers.

I want to reload table view automatically when only when values in array changes or updated.

For this, I want to add observer on mutable array i.e when values in array changes then it should call a particular method for e.g

-(void)ArrayUpdatedNotification:(NSMutableArray*)array
{
    //Reload table or do something
} 

Thanks in advance.

解决方案

What is can do is - After updating your Array send a Notification (NSNotificationCenter) and this notification will be received by all the controllers. On receiving the notificaiton the controller should do [tableview reloaddata].

Code example:

// Adding an observer
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTable:) name:@"arrayUpdated" object:nil];

// Post a notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"arrayUpdated" object:nil]; 

// the void function, specified in the same class where the Notification addObserver method has defined
- (void)updateTable:(NSNotification *)note { 
    [tableView reloadData]; 
}

这篇关于如何在NSMutableArray上添加观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆