【问题标题】:How to get specific JSON data in UITableView when Button is clicked in iOS(objective c)?在iOS中单击按钮时如何在UITableView中获取特定的JSON数据(目标c)?
【发布时间】:2017-04-11 13:15:50
【问题描述】:

我的 JSON 数据如下所示:

 {
      "success": true,
      "data": [
        {
      "playerId": "j_mohammed",
      "playerName": "Jason Mohammed",
      "playerShortName": "Jason Mohammed",
      "PlayingRole": 3,
      "Credit": 85,
      "Player_Points": 45,
      "TeamName": "wi",
      "TeamColor": "1"
    },
    {
      "playerId": "s_gabriel",
      "playerName": "Shannon Gabriel",
      "playerShortName": "ST Gabriel",
      "PlayingRole": 4,
      "Credit": 80,
      "Player_Points": 0,
      "TeamName": "wi",
      "TeamColor": "1"
    },
    {
      "playerId": "s_hope",
      "playerName": "Shai Hope",
      "playerShortName": "S Hope",
      "PlayingRole": 1,
      "Credit": 85,
      "Player_Points": 0,
      "TeamName": "wi",
      "TeamColor": "1"
    },
    {
      "playerId": "e_lewis",
      "playerName": "Evin Lewis",
      "playerShortName": "Evin Lewis",
      "PlayingRole": 3,
      "Credit": 85,
      "Player_Points": 281,
      "TeamName": "wi",
      "TeamColor": "1"
    },
   {
      "playerId": "m_hafeez",
      "playerName": "Mohammad Hafeez",
      "playerShortName": "Mohammad Hafeez",
      "PlayingRole": 2,
      "Credit": 90,
      "Player_Points": 0,
      "TeamName": "pak",
      "TeamColor": "4"
    },
    {
      "playerId": "f_ashraf",
      "playerName": "Fahim Ashraf",
      "playerShortName": "Fahim Ashraf",
      "PlayingRole": 3,
      "Credit": 85,
      "Player_Points": 0,
      "TeamName": "pak",
      "TeamColor": "4"
    }
  ]
}

我已经将此 JSON 解析到我的应用程序中。 我的应用程序的视图如下所示:

因为它显示我在视图顶部有 4 个按钮:

我在 ViewController 中使用了 TableView 来解析数据:

这就是我所做的。现在我的主要问题是,当我单击按钮“WK”时,我只想在 tableview 中显示来自 JSON 的检票员列表,当我单击“BAT”时,击球手的列表等等。我现在已经完成了解析,它显示了所有来自 JSON 的数据,不知道如何在单击按钮时在 TableView 中显示选定的数据。

无论球员是投球手、击球手还是三柱门守门员,它都以 JSON 格式存储为 "PlayingRole"。 所以,如果玩家是Wicket keeper its role is:1 All rounder:2 Batsman:3 Bowler:4

这是我完成的代码:

NSString *mainurl = [NSString stringWithFormat:@"http://192.168.1.102/redbull11/webservices/api/getMatcheSquad/“];

NSString *playerurl = [NSString stringWithFormat:@"%@%@",mainurl,match_id2];

NSURL *url=[NSURL URLWithString:playerurl];

NSLog(@"mainurl: %@",url);

NSURLSessionConfiguration *csc=[NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *csession = [NSURLSession sessionWithConfiguration:csc delegate:nil delegateQueue:[NSOperationQueue mainQueue]];

NSURLSessionDataTask *ctask=[csession dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

getsuccess = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];               

dispatch_async(dispatch_get_main_queue(), ^{

 NSString *success =[getsuccess valueForKey:@"success"];

 if([success boolValue] == YES)

 {   

NSArray *arr =[getsuccess valueForKey:@"data"];

for ( NSDictionary *dic2 in arr) {

NSMutableArray *temp =[[NSMutableArray alloc]init];

[temp addObject:[dic2 valueForKey:@"playerShortName"]];

[temp addObject:[dic2 valueForKey:@"Credit"]];

[temp addObject:[dic2 valueForKey:@"Player_Points"]];

[temp addObject:[dic2 valueForKey:@"TeamName"]];

[temp addObject:[dic2 valueForKey:@"PlayingRole"]];

[getLoc addObject:temp];

}}

 NSLog(@"%@",getLoc);

 [_playerselect reloadData];

[MBProgressHUD hideHUDForView:self.view animated:YES];

 });

});

 }];

[ctask resume];

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

    selectTeamCell *cell = [tableView dequeueReusableCellWithIdentifier:@"names" forIndexPath:indexPath];
    NSMutableArray *arr =[[NSMutableArray  alloc]init];

    arr = [getLoc objectAtIndex:indexPath.row];
    NSLog(@"%ld",(long)indexPath.row);

    cell.playerName.text = [arr objectAtIndex:0];
    cell.playerCredit.text = [[arr objectAtIndex:1]stringValue];
    cell.playerPoints.text = [[arr objectAtIndex:2]stringValue];
    cell.teamName.text = [arr objectAtIndex:3];
   return cell;
}

请帮忙。提前谢谢你。

【问题讨论】:

  • 还有...你的代码是什么?
  • @Maulik Desai Parse json 根据您的要求创建两个数组,一个用于击球手,一个用于守门员附加适当的数据。并相应地获取它们。
  • @AlejandroIván 看到我已经编辑了问题。
  • 检票员钥匙在哪里?
  • @DishantRajput in JSON "PlayingRole": 1 表示 wicketkeeper。

标签: ios objective-c json uitableview


【解决方案1】:

如果您只想显示检票员。这只是为了在表格视图单元格中显示检票员

1.) 将您的响应存储在一个数组中。

NSArray *yourArray =[getsuccess valueForKey:@"data"];//please declare your array globally

那么

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return yourArray.count;
}

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

selectTeamCell *cell = [tableView dequeueReusableCellWithIdentifier:@"names" forIndexPath:indexPath];


NSDictionary *dictYourDict;
dictYourDict=[yourArray objectAtIndex:indexPath.row];

cell.yourLabel.text=[dictYourDict objectForkEy : @"PlayingRole"];

return cell;
 }

【讨论】:

  • 感谢您的努力。正如你所说,它正在显示检票员。但是当我点击不同的按钮时,我想在守门员、击球手、投球手和全能手之间进行切换。
  • 然后您可以做的是拥有另一个属性,该属性指示您要显示哪种类型的数据@property (strong, nonatomic) NSString *typeOfData; 并使用tableView:cellForRowAtIndexPath: 中的一个或另一个信息。最简单的方法是为每种类型的选择实际使用不同的数组。您的按钮的IBAction 应该定义该属性并调用[tableView reloadData];
  • 是的,我知道伙计。我只是告诉你的方法。您必须在每次点击中设置一个变量并在 ibaction 中调用它。并重新加载您的表格视图。
  • @AlejandroIván 和thanx 的帮助我已经按照你们的建议做了同样的事情。我已经通过混合你的建议和我的编码解决了这个问题!
【解决方案2】:

使用此谓词过滤数据

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"PlayingRole == 1"];
NSArray *arrWicketKeeper = [arrMain filteredArrayUsingPredicate:predicate];

【讨论】:

    【解决方案3】:

    我已经解决了我的问题,这是我在代码中所做的:

    @implementation selectTeam{
    int flag;
    }
    - (void)viewDidLoad {
    [super viewDidLoad];
    flag = 1;
    NSString *mainurl = [NSString stringWithFormat:@"http://192.168.1.102/redbull11/webservices/api/getMatcheSquad/"];
    NSString *playerurl = [NSString stringWithFormat:@"%@%@",mainurl,match_id2];
    NSURL *url=[NSURL URLWithString:playerurl];
    NSLog(@"mainurl: %@",url);
    NSURLSessionConfiguration *csc=[NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *csession = [NSURLSession sessionWithConfiguration:csc delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *ctask=[csession dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
      {
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    getsuccess = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    dispatch_async(dispatch_get_main_queue(), ^{
    NSString *success =[getsuccess valueForKey:@"success"];
     if([success boolValue] == YES)
     {
    NSArray *arr =[getsuccess valueForKey:@"data"];
    for ( NSDictionary *dic2 in arr) {
    NSMutableArray *temp =[[NSMutableArray alloc]init];
    playerrole = [[dic2 valueForKey:@"PlayingRole"]stringValue];
    NSLog(@"role: %@",playerrole);
    if ([playerrole isEqual:@"1"]) {
    [temp addObject:[dic2 valueForKey:@"playerShortName"]];
    [temp addObject:[dic2 valueForKey:@"Credit"]];
    [temp addObject:[dic2 valueForKey:@"Player_Points"]];
    [temp addObject:[dic2 valueForKey:@"TeamName"]];
    [temp addObject:[dic2 valueForKey:@"PlayingRole"]];
    [wkeeper addObject:temp];
    }
     else if ([playerrole isEqual:@"2"]) {
    [temp addObject:[dic2 valueForKey:@"playerShortName"]];
    [temp addObject:[dic2 valueForKey:@"Credit"]];
    [temp addObject:[dic2 valueForKey:@"Player_Points"]];
    [temp addObject:[dic2 valueForKey:@"TeamName"]];
    [temp addObject:[dic2 valueForKey:@"PlayingRole"]];
    [allrounder addObject:temp];
    }
    else if ([playerrole isEqual:@"3"])
     { [temp addObject:[dic2 valueForKey:@"playerShortName"]];
    [temp addObject:[dic2 valueForKey:@"Credit"]];
    [temp addObject:[dic2 valueForKey:@"Player_Points"]];
    [temp addObject:[dic2 valueForKey:@"TeamName"]];
     [temp addObject:[dic2 valueForKey:@"PlayingRole"]];
    [batsman addObject:temp];
     }
     else if ([playerrole isEqual:@"4"])
    {
     [temp addObject:[dic2 valueForKey:@"playerShortName"]];
    [temp addObject:[dic2 valueForKey:@"Credit"]];
    [temp addObject:[dic2 valueForKey:@"Player_Points"]];
    [temp addObject:[dic2 valueForKey:@"TeamName"]];
    [temp addObject:[dic2 valueForKey:@"PlayingRole"]];
    [bowler addObject:temp];
     }}}
    [_playerselect reloadData];
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
    });
    }];
    [ctask resume];
    
    
    
    - (IBAction)wicketkeeper:(id)sender {
        flag=1;
     _pickplayers.text= @"PICK 1 WICKET-KEEPER";
        [_playerselect reloadData];    
    }
    - (IBAction)batsman:(id)sender {
        flag=3;
        _pickplayers.text= @"PICK 3-5 BATSMEN";
        [_playerselect reloadData];
    }
    - (IBAction)allrounder:(id)sender {
        flag=2;
        _pickplayers.text= @"PICK 1-3 ALL-ROUNDERS";
        [_playerselect reloadData];   
    }
    - (IBAction)bowler:(id)sender {
        flag=4;
        _pickplayers.text= @"PICK 3-5 BOWLERS";
        [_playerselect reloadData];    
    }
    
    
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        selectTeamCell *cell = [tableView dequeueReusableCellWithIdentifier:@"names" forIndexPath:indexPath];
        NSMutableArray *arr =[[NSMutableArray  alloc]init];
    if (flag==1){
            arr = [wkeeper objectAtIndex:indexPath.row];
            NSLog(@"%ld",(long)indexPath.row);
        }
        else if (flag==2){
            arr = [allrounder objectAtIndex:indexPath.row];
            NSLog(@"%ld",(long)indexPath.row);
        }
        else if (flag==3){
            arr = [batsman objectAtIndex:indexPath.row];
            NSLog(@"%ld",(long)indexPath.row);
        }
        else{
            arr = [bowler objectAtIndex:indexPath.row];
            NSLog(@"%ld",(long)indexPath.row);
    }
        cell.playerName.text = [arr objectAtIndex:0];
        cell.playerCredit.text = [[arr objectAtIndex:1]stringValue];
        cell.playerPoints.text = [[arr objectAtIndex:2]stringValue];
        cell.teamName.text = [arr objectAtIndex:3];
       return cell;
    }
    

    【讨论】:

    • 很高兴您设法解决了您的问题。作为一个建议,你可以通过在 Objective-C 中使用新的语法来清理你的代码。例如,您可以简单地执行someArray[number] 而不是[someArray objectAtIndex:number],效果相同。这也适用于NSDictionary,您可以在其中使用someDictionary[@"key"] 而不是[someDictionary valueForKey:@"key"]。编码愉快!
    • 要初始化NSArrayNSNumberNSDictionary,你可以使用literal syntax
    • @AlejandroIván 谢谢你的建议兄弟!!我已经按照你的建议做了!!谢谢你的帮助!!
    猜你喜欢
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2017-07-01
    相关资源
    最近更新 更多