设置cell.textlabel。文本从json数组

时间:2022-01-29 10:42:31

Hello I'm trying to parse data from json and get the values to show in cells.

你好,我正在解析json数据并获取要在单元格中显示的值。

Here is my ViewController.h

这是我ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UITableView *mainTableView;
    NSMutableData *data;
}
@property (nonatomic, strong) NSArray *category;
@property (nonatomic, strong) NSArray *coursesArray;
@property (nonatomic, strong) NSDictionary *parsedData;

@end

This is what I have in ViewController.m

这是我在ViewController.m中所拥有的。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    parsedData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    coursesArray = [parsedData valueForKey:@"courses"];
    NSLog(@"coursesArray: %@", coursesArray);
    category = [coursesArray valueForKey:@"category"];
    NSLog(@"%@", category);
}
-(int)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:@"MainCell"];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"%@", [category objectAtIndex:indexPath.row]];
    NSLog(@"%@", category);
    return cell;
}

At connectionDidFinishLoading I see in the log the right values, but when I try to check them before the cell is created I get null. What I'm doing wrong here?

在connectionDidFinishLoading中,我在日志中看到了正确的值,但是当我试图在创建单元格之前检查它们时,我得到了null。我做错了什么?

2 个解决方案

#1


1  

Call

调用

 [mainTableView reloadData];

inside your -connectionDidFinishLoading: method.

在你-connectionDidFinishLoading:方法。

#2


0  

Make sure your category array is not released/autoreleased.

确保您的类别数组没有被释放/自动加载。

#1


1  

Call

调用

 [mainTableView reloadData];

inside your -connectionDidFinishLoading: method.

在你-connectionDidFinishLoading:方法。

#2


0  

Make sure your category array is not released/autoreleased.

确保您的类别数组没有被释放/自动加载。