【问题标题】:How to populate UITableView with JSON data?如何使用 JSON 数据填充 UITableView?
【发布时间】:2015-03-05 14:52:38
【问题描述】:

我正在努力找出我做错了什么。我基本上是在尝试用 json 数据填充我的 UITableView。在控制台中我可以看到结果,但只是不知道为什么数据没有显示在 tableview 中。我看过类似的问题和答案,但没有一个可以解决我的问题。

请提供建议或帮助;

#pragma mark - Private method implementation

-(void)loadData{
    // Form the query.
    @try {


        NSString *get =[[NSString alloc] initWithFormat:@""];
        NSString *getRegions = [NSString stringWithFormat:@"JSON URL HERE",self.sessionId, self.companyId];
        NSURL *url=[NSURL URLWithString:getRegions];
        NSLog(@"Get regions: %@", url);
        NSData *postData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"GET"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setHTTPBody:postData];

        //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Reponse code: %ld", (long)[response statusCode]);
        if ([response statusCode] >= 200 && [response statusCode] < 300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);
            @try{
                NSError *error = nil;
                regionsJson = [[NSMutableArray alloc]init];
                //[jsonData removeAllObjects];
                regionsJson = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];

                NSArray *tblArray = [NSArray arrayWithObject:regionsJson];
            }
            @catch (NSException *e){
                NSLog(@"Try catch block: %@", e);
            }
            @finally{
                // [self.tblRegion reloadData];
                NSLog(@"finally");
            }


            structureJson =[regionsJson valueForKey:@"structure"];
            companyJson =[structureJson valueForKey:@"company"];
            _barBtnCompanyName.title = [companyJson valueForKey:@"company_name"];
            NSLog(@"Get company name: %@", [companyJson valueForKey:@"company_name"]);

            for  (int i =0 ; i < regionsJson.count; i++){
                regionsJson = [companyJson objectForKey:@"regions"];
                NSString *regionName = [NSString stringWithFormat:@"%@", [regionsJson valueForKey:@"region_name"]];
                NSLog(@"Region name: %@",regionName);
                // [regionsJson addObject:regionName];
                 NSString *alarmCount = [NSString stringWithFormat:@"%@", [regionsJson valueForKey:@"alarm_cnt"]];
                 NSLog(@"Alarm count: %@", alarmCount);
                 // [regionsJson addObject:alarmCount];

             }

        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);

    }
    // Reload the table view.
    [self.tblRegion reloadData];

}


#pragma mark - UITableView method implementation

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"Number of rows: %lu", (unsigned long)regionsJson.count);
    return [regionsJson count];

}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"CellRegions";
    // Dequeue the cell.
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    // Set the loaded data to the appropriate cell labels.
     cell.textLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:@"region_name"];
     cell.detailTextLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:@"alarm_cnt"];

    [cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
    NSLog(@"Table cell: %@", cell);
    return cell;
}

【问题讨论】:

  • 在主线程中尝试[self.tblRegion reloadData];
  • 我已经尝试过,tableview 中仍然没有显示任何内容。 -(void)viewDidLoad{ [超级 viewDidLoad]; // 加载视图后做任何额外的设置。 [self.tblRegion reloadData]; [自加载数据]; }
  • 我的主线程,一旦你用dispatch_get_main_queue得到了JSON数据
  • 请发表您的答案。我会很感激,因为我还在学习objective-c 我不知道dispatch_get_main_queue。

标签: ios json uitableview nsmutablearray nsdictionary


【解决方案1】:

我的代码很好,我愚蠢地省略了这个声明。

-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tblRegion.delegate = self;
self.tblRegion.dataSource = self;
 [self loadData];

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多