从AppDelegate.m重新加载TableView数据?

时间:2014-10-15 16:08:18

标签: ios objective-c xcode

我尝试从appDelegate重新加载tableView

在AppDelegate.m中,在负责推送通知的方法中,“didReceiveRemoteNotification”我每次收到通知时都会调用UIAlertView。

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notification received" message:[NSString stringWithFormat:@"%@", titleMsg]  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                alertView.delegate = self;
                [alertView show];

当用户单击“确定”按钮时,应该是读取数据库并重新加载tableview

// Reload the table when the user click "OK" button in the alert
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if ([alertView.title isEqualToString:@"Notification received"])
{
    if (buttonIndex == [alertView cancelButtonIndex])
    {
        // Stop the sound for notifications
        [self stopSoundForNotifications];

        // Refresh table messages 
        AccueilViewController * avc = [[AccueilViewController alloc] init];
        [avc readMsgsFromDB];
        [avc reloadTableMsgsReceived];

        [[NSNotificationCenter defaultCenter] postNotificationName:@"ReadMessagesFromDB" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadDataFromDelegate" object:nil];
    }
}

}

在标题中,我添加到协议UIAlertViewDelegate

你有什么想法吗?感谢

2 个答案:

答案 0 :(得分:0)

您将条件设置为取消按钮而不是将条件设置为确定按钮 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

if ([alertView.title isEqualToString:@"Notification received"])
{
    if (buttonIndex == [alertView OKButtonIndex])
    {
        // then fire notification
        // Stop the sound for notifications
        [self stopSoundForNotifications];

        // Refresh table messages 
        AccueilViewController * avc = [[AccueilViewController alloc] init];
        [avc readMsgsFromDB];
        [avc reloadTableMsgsReceived];

        [[NSNotificationCenter defaultCenter] postNotificationName:@"ReadMessagesFromDB" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadDataFromDelegate" object:nil];
    }
}

答案 1 :(得分:0)

看起来您正在创建AccueilViewController的新实例,而不是访问现有实例。因此,readMsgsFromDBreloadTableMsgsReceived正由一个不可见的实例处理。

如果您修改了AccueilViewController代码,则可以注册接收这些通知,然后您的现有实例可以对其进行操作以重新加载数据。实际上,我只使用一个通知,并将两个方法调用合并为一个。

请删除第二个postNotification,然后在AccueilViewController中将以下内容添加到viewDidLoad方法中:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationReceived) name:@"ReadMessagesFromDB" sender:nil];

然后添加一个方法来组合这两个动作:

-(void)notificationReceived {
    [self readMsgsFromDB];
    [self reloadTableMsgsReceived];
}

因此,当您按下AlertView按钮时,将发布通知。将触发现有notificationReceived实例中的AccueilViewController方法,从而从数据库和要重新加载的表中读取消息。您还应该添加一个调用,以便在取消分配之前从通知中心删除视图控制器:

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"ReadMessagesFromDB" object:nil];