0

我想填充TableViewContoller中的TableViewCells與正從一個JSON對象拉的數據的數組。 NSJSONSerialization根本沒有被調用。NSJSONSerialization沒有被調用 - 目標C

我試過使用DataTaskWithURL的各種東西。可悲的是,我在數組中找到了0個項目。在此先感謝任何人的幫助!

@property NSArray *toothpastes; 

@end 

@implementation ToothpastChoicesTableViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSString *urlString = @"https://s3.amazonaws.com/mmios8week/toothpastes.json"; 
    NSURLSession *session = [NSURLSession sharedSession]; 

    [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^ 
    (NSData *data, 
     NSURLResponse *response, 
     NSError *error) { 

     if (error) { 
     NSLog(@"%@", error); 
    } else { 

    self.toothpastes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; 
    [self.tableView reloadData]; } 

    }]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    NSLog(@"%lu", (unsigned long)self.toothpastes.count); 

    return self.toothpastes.count; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID" forIndexPath:indexPath]; 

    cell.textLabel.text = self.toothpastes[indexPath.row]; 

    return cell; 
} 
+0

打印出來的錯誤。 – vadian

+0

嗨@vadian - 我試過記錄錯誤,但沒有顯示。我已經更新了代碼以包含它。思考?謝謝參觀。 –

+0

完成塊是否被調用?記錄'self.toothpastes' - 你應該重新加載主線程上的表格視圖。 – vadian

回答

0

你忘了恢復任務

NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

    if (error) { 
     NSLog(@"%@", error); 
    } else { 

    self.toothpastes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; 
    [self.tableView reloadData]; 
    } 
    }]; 
[task resume]; 
+0

謝謝@vadian!奇蹟般有效。感謝幫助先生。 –