数据同时显示在两个屏幕上

时间:2014-08-09 10:52:40

标签: ios objective-c

在我的应用程序中有一个侧面菜单和主屏幕,

enter image description here

数据来自Web服务,它返回JSON对象,

在JSON对象类别中,如1,2,3,4 ....及其相关描述,如图像和价格等。

首先调用侧边菜单类的ViewDidLoad,然后调用主屏幕类,因此我使用NSURLConnection对象在侧边菜单类中调用了我的Web服务。

- (void)viewDidLoad
{

NSString *url_str=[NSString stringWithFormat:@"myurl.php"];
    NSURL *url=[NSURL URLWithString:url_str];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];

    NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [response_data appendData:data];
}

-(void)connection: (NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [response_data setLength:0];
}

-(void)connection :(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR WITH CONNECTION");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *myError;
    table_data=[NSJSONSerialization JSONObjectWithData:response_data options:NSJSONReadingMutableLeaves error:&myError];
    NSLog(@"JSON data  %@",table_data);
    [self.tableView reloadData];
}

响应数据在主ViewDidLoad方法之后正常运行。因此我无法获取主屏幕的数据。

任何人都可以帮助我在获得网络服务响应后如何在两个屏幕上同时显示数据。

1 个答案:

答案 0 :(得分:1)

如果您有多个位置,您希望在操作完成后让UI响应(即通过显示已加载数据的结果),您可以使用NSNotificationCenter来广播通知。

在您的connectionDidFinishLoading方法中,您需要发送如下通知:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *myError;
    table_data=[NSJSONSerialization JSONObjectWithData:response_data options:NSJSONReadingMutableLeaves error:&myError];
    NSLog(@"JSON data  %@",table_data);
    [self.tableView reloadData];

    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:table_data forKey:@"table_data"];
    [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"DataLoadedNotification" 
        object:nil userInfo:userInfo];

}

在主屏幕中,您可以通过viewDidLoad方法执行以下操作来收听通知并在屏幕上重新绘制数据:

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

当然,您需要实现在收到通知时将被调用的方法:

- (void) receiveDataLoadNotification:(NSNotification *) notification
{
    // [notification name] should always be @"DataLoadedNotification"
    // unless you use this method for observation of other notifications
    // as well.

    if ([[notification name] isEqualToString:@"DataLoadedNotification"])
    {
        NSDictionary *userInfo = notification.userInfo;
        JSONObject *table_data = [userInfo objectForKey:@"table_data"];
        NSLog (@"Successfully received the data loaded notification!");
    }
}

如果需要,可以拉取table_data对象

相关问题