繁体   English   中英

我无法从JSON获取数组以加载到UITableView中

[英]I can't get my array from JSON to load into the UITableView

.h包含

@interface HomeTVC : UITableViewController
@property (nonatomic, strong) NSArray *spotTitle;

.m包含

#import "HomeTVC.h"

@interface HomeTVC ()

@end

@implementation HomeTVC

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

这是我发出服务器请求并获取数据的地方

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL *homeDataURL = [NSURL URLWithString:@"XXXXX"];
    NSData *jsonSpots = [NSData dataWithContentsOfURL:homeDataURL];
    NSDictionary *spotTableDictionary = [NSJSONSerialization JSONObjectWithData:jsonSpots options:0 error:NULL];
    NSArray *spotTitle = [spotTableDictionary valueForKey:@"title"];
    NSLog(@"%@",spotTitle);

NSLog打印我想传递到终端中的tableview的数组,这里的一切似乎都正常工作。

这是我的问题开始的地方:

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.spotTitle count];
}

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

    cell.textLabel.text = [self.spotTitle objectAtIndex:indexPath.row];
    return cell;
}

我一直在摸索尝试将传递给该NSLog语句的数组连接到我的表视图,但现在不确定我在做什么错。

dataSourcedelegate都连接到主故事板上的HomeTVC。

该程序将编译并运行,没有错误或警告,并加载一个空的tableview。

也许我缺少一些超级基础的东西(我真的是编程新手),这是我第一次尝试传入外部数据库。

NSArray *spotTitle = [spotTableDictionary valueForKey:@"title"];
self.spotTitle = spotTitle; //Do you forget assign to your property?
NSLog(@"%@",self.spotTitl);

当可以使用属性时,为什么还要创建另一个变量。 只是这样做:

- (void)viewDidLoad
{
    [super viewDidLoad];

NSURL *homeDataURL = [NSURL URLWithString:@"XXXXX"];
NSData *jsonSpots = [NSData dataWithContentsOfURL:homeDataURL];
NSDictionary *spotTableDictionary = [NSJSONSerialization JSONObjectWithData:jsonSpots options:0 error:NULL];
self.spotTitle = [spotTableDictionary valueForKey:@"title"];
NSLog(@"%@",self.spotTitle);

那应该解决您的问题。 也不要对属性和局部变量使用相同的名称,否则在您处理时会导致不必要的混乱。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM