【问题标题】:ios - How to load data from JSON url in UITableView?ios - 如何从 UITableView 中的 JSON url 加载数据?
【发布时间】:2013-05-26 23:49:38
【问题描述】:

我是 iPhone 开发的新手,我正在尝试将来自 JSON 网址的数据绑定到 UITableview,但在下面的代码中出现错误。

- (void)viewDidLoad
{

SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://80f237c226fa45aaa09a5f5c82339d46.cloudapp.net/DownloadService.svc/Courses"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
statuses = [parser objectWithString:json_string error:nil];
[self.dropdownTblView reloadData];
for (NSDictionary *status in statuses) 
{
    _altTitle = [status valueForKey:@"Title"];
    NSLog(@"Title %@",_altTitle);
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   NSLog(@"%d",[statuses count]);
   return [statuses count];

}

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

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;

 //Here I'm getting an error    
id obj = [statuses objectAtIndex:indexPath.row];
NSString *name = [obj valueForKey:@"Title"];
cell.textLabel.text =name;
return cell;
}

这是我的 JSON

[
  {
    "Id": 1,
    "Title": "Tamil to English",
    "AltTitle": "த|மி|ழ்| |மூ|ல|ம்| |ஆ|ங்|கி|ல|ம்",
    "Description": "Learn English through Tamil",
    "Code": 1,
    "Version": "1.0",
    "SourceLanguageIndicator": "அ",
    "TargetLanguageIndicator": "A",
    "SourceLanguageCode": "ta",
    "TargetLanguageCode": "en",
    "Updated": "2013-02-21T03:33:19.6601651+00:00"
  }    
]    

有什么想法吗?提前致谢。

【问题讨论】:

  • 你遇到了什么错误?
  • 所以?错误是什么?
  • 您在同一范围内返回单元格两次,请尝试删除第一个return cell;
  • 检查返回的状态是什么?我的意思是,一旦你得到解析的数据,只需打印并检查它是字典还是数组。然后删除第一个返回单元格语句。
  • 能否告诉我们您遇到了什么错误。

标签: iphone ios json uitableview


【解决方案1】:

您在同一范围内两次返回单元格,尝试删除第一个return cell;,同时您在for 循环之前的表上调用reloadData;在这种情况下,表的 dataSource 可能仍然是空的,所以在 for 循环之后调用 reloadData

编辑: 发生了什么很奇怪,objectFromStringmust returnNSArrayNSDictionary,但似乎指向NSSet。我还可以建议两件事:

  1. 您似乎没有使用 ARC,因为您在 UITableViewCell 上调用 autorelease。在这种情况下,您在viewDidLoad 中泄漏了parserjson_string,所以release 他们。

  2. 确保调用[super viewDidLoad];(您的代码中没有这样做)。

【讨论】:

  • 感谢您的宝贵回复,但我仍然遇到错误
  • @user2439531 你的错误是什么?另外,我不明白你是否使用 ARC。
  • 节目接收信号:“EXC_BAD_ACCESS”。
  • 您是否按照我的回复中所述将[self.dropdownTblView reloadData]; 放在for 循环之后?也许设置一个断点来检查哪一行引发了错误。
  • 正是这里 id obj = [statuses objectAtIndex:indexPath.row];
【解决方案2】:

可能是因为您将obj 的类型设置为id。太笼统了,可能不知道怎么回复valueForKey。您是否尝试过将obj 声明为NSDictionary *?就像下面的代码:

NSDictionary *obj = [statuses objectAtIndex:indexPath.row];
NSString *name = [obj valueForKey:@"Title"];

【讨论】:

  • 我认为这不是问题所在。既然他知道有字典,那么设置为id就可以了。
【解决方案3】:

在您的ViewDidload 中使用下面的代码并运行项目,它将起作用。

注意:您要返回单元格两次,请尝试删除第一次返回 细胞;

- (void)viewDidLoad
{
    [super viewDidLoad];

    statuses=[[NSMutableArray alloc]init];

    NSURL *myURL = [NSURL URLWithString:@"http://80f237c226fa45aaa09a5f5c82339d46.cloudapp.net/DownloadService.svc/Courses"];


    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];


    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]

                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                               NSLog(@"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
                              id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];


                                NSLog(@"jsonObject=%@",jsonObject);

                               statuses=[jsonObject mutableCopy];

                               [self.coursetable reloadData];
                           }];

    NSLog(@"myURL=%@",myURL);

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"%d",[statuses count]);
    return [statuses count];

}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    }

    id obj = [statuses objectAtIndex:indexPath.row];
    cell.textLabel.text =[obj valueForKey:@"Title"];

    return cell;
}

【讨论】:

  • 感谢您的回复,我使用的是 Xcode 3.2 所以不支持 NSJSONSerialization
  • 好了,剩下的就用剩下的了,就用下面的方法 Nsarray *myarray = [parser objectWithString:json_string error:nil]; statuses=[myarray mutableCopy];然后重新加载 Tableview。
【解决方案4】:

是的,我想对了,status 不是 NSArray,它是 NSSet,所以如果你在 NSSet 上调用 objectAtIndex,它会崩溃。要让数组将 NSSet 转换为 NSArray。

NSArray *array =[statuses allObjects];  

【讨论】:

  • 可能是的,但我想知道为什么objectFromString 返回的是一个集合而不是一个数组? objectFromString 的文档说:The NSArray or NSDictionary represented by the object, or nil if an error occured.
  • 打印状态并检查返回的内容,NSArray 还是 NSDictionary?
  • 能否请您说明您得到了什么。只需打印为 NSLog(@"%@", [parser objectWithString:json_string error:nil]; );。无需分配给任何对象。
【解决方案5】:
 - (void)viewDidLoad
   {

  NSString *dictStr=@"{\"Id\": 1,\"Title\": \"Tamil to English\",\"AltTitle\": \"த|மி|ழ்| |மூ|ல|ம்| |ஆ|ங்|கி|ல|ம்\",\"Description\": \"Learn English through Tamil\",\"Code\": 1,\"Version\": \"1.0\",\"SourceLanguageIndicator\": \"அ\",\"TargetLanguageIndicator\": \"A\",\"SourceLanguageCode\": \"ta\",\"TargetLanguageCode\": \"en\",\"Updated\": \"2013-02-21T03:33:19.6601651+00:00\"}";

 NSDictionary *rootDict =[NSJSONSerialization JSONObjectWithData: [dictStr dataUsingEncoding:NSUTF8StringEncoding]
                                    options: NSJSONReadingMutableContainers
                                      error: nil];
     NSArray *keys=[[rootDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
   }

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

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

     if (cell==nil) {
      cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
     }

      cell.textLabel.text=[rootDict valueForKey:[keys objectAtIndex:indexPath.row]];
      return cell;
  }

记住 rootDict 和键将被声明为全局。

【讨论】:

    猜你喜欢
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 2016-07-14
    • 1970-01-01
    • 2014-09-20
    相关资源
    最近更新 更多