实时iphone更新收藏列表

时间:2011-09-30 09:58:05

标签: iphone uitableview

我的应用程序有两个选项卡,其中一个是表格视图,在另一个选项卡中我可以将当​​前对象添加到核心数据存储中,我希望表格视图可以在我完成的任何时候都是最新的添加并切换回该选项卡(表格视图)。目前,表视图仅在我的应用程序重新启动时刷新,这是可以理解的,因为我在该viewController中的viewDidLoad方法中获取数据。当我在这两个选项卡之间来回切换时,他们的视图已经加载,那么如何实时更新表视图?任何建议将不胜感激。

更新

一个很好的例子是iphone上的联系人应用程序,但我不知道该怎么做......


这是表视图控制器中的一些代码。

- (void)viewDidLoad {
    [super viewDidLoad];

    bList = [[NSMutableArray alloc] init];

    self.navigationItem.leftBarButtonItem = self.editButtonItem;

      //some code to get data from core data storage and put them in the bList array.

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(receiveAddNotification:) 
                                             name:@"AddNotification"
                                           object:nil];
}

-(void) receiveAddNotification: (NSNotification *)notification{
    if ([[notification name] isEqualToString:@"AddNotification"]){
        NSLog (@"Successfully received the add notification!");
    }
}

其他选项卡的视图控制器中的代码。

-(IBAction) addSomething {

    [[NSNotificationCenter defaultCenter] postNotificationName:@"AddNotification" object:self];
        //some code to store an object in core data.
}

控制台可以输出消息“成功收到添加通知!”,这意味着通知正常,但是当我从编辑选项卡切换回表视图选项卡时,表视图没有刷新。我假设addSomething方法中新添加的对象应该更新为receiveAddNotification:方法。

1 个答案:

答案 0 :(得分:1)

嗨迈克尔,因为我理解你的问题,你可以使用通知概念。在表视图控制器中启动通知服务,当您完成添加内容后,您可以发布通知,以便自动更新表视图。

查看 NSNotificationCenter

让我用一个例子来解释。

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(receiveTestNotification:) 
                                             name:@"TestNotification"
                                           object:nil];

在表视图控制器中添加以上语句。然后,您只需使用[tableview reload];

定义“receiveTestNotification:”函数

在编辑视图控制器中,当用户点击完成按钮时,您发布通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self];

因此它会调用“receiveTestNotification:”方法并运行代码,无论你在该方法中给出了什么。