简体   繁体   English

ios-如何从UITableView中的JSON URL加载数据?

[英]ios - How to load data from JSON url in UITableView?

I'm new to iPhone development,I'm trying to bind data from JSON Url in UITableview , but I'm getting an error in the below code. 我是iPhone开发的新手,正在尝试从UITableview JSON Url绑定数据,但是在以下代码中出现错误。

- (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;
}

This is my JSON 这是我的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"
  }    
]    

Any ideas? 有任何想法吗? Thanks in advance. 提前致谢。

Maybe because you set the type of obj as id . 可能是因为您将obj的类型设置为id It is too generic and may not know how to respond to valueForKey . 它太通用了,可能不知道如何响应valueForKey Have you tried declaring obj as an NSDictionary * instead? 您是否尝试过将obj声明为NSDictionary * Like the code below: 像下面的代码:

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

You're returning the cell twice in the same scope, try to delete the first return cell; 您要在同一范围内两次返回该单元格,请尝试删除第一个return cell; , also you're calling reloadData on the table just before the for loop; ,也就是在for循环之前在表上调用reloadData in this case probably the dataSource of the table is still empty, so call reloadData just after the for loop. 在这种情况下,表的dataSource可能仍然为空,因此请在for循环之后调用reloadData

EDIT: It's strange what is happening, the objectFromString must return a NSArray or a NSDictionary but it seems that is pointing to an NSSet . 编辑:发生了什么事很奇怪, objectFromString 必须返回 NSArrayNSDictionary但似乎指向NSSet I can suggest 2 things in addition: 我可以建议另外两件事:

  1. It seems that you're not usig ARC since you're calling autorelease on the UITableViewCell . 似乎您不是usig ARC,因为您正在UITableViewCell上调用autorelease In this case you're leaking parser and json_string in the viewDidLoad , so release them. 在这种情况下,您将在viewDidLoad泄漏parserjson_string ,因此请release它们。

  2. Make sure to call [super viewDidLoad]; 确保调用[super viewDidLoad]; (you're not doing this in your code). (您没有在代码中这样做)。

Use the Below code in your ViewDidload and Run the Project , it will work. ViewDidload使用以下代码并运行Project,它将起作用。

Note :You're returning the cell twice, try to delete the first return cell; 注意:您要返回两次该单元格,请尝试删除第一个返回单元格;

- (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;
}
 - (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;
  }

remember rootDict and keys will be declared as global. 请记住,rootDict和键将被声明为全局。

是的,我想的没错,状态不是NSArray,而是NSSet,因此如果在NSSet上调用objectAtIndex它将崩溃。要获取数组,请将NSSet转换为NSArray。

NSArray *array =[statuses allObjects];  

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

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