簡體   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