0

I am new to the iOS , When i am implementing to fetch the data from api , i am getting the -[__NSCFDictionary objectAtIndex:]: error.

Code:

Request Dispatching

-(void)JobTakeFive{

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

    //NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.json-generator.com/api/json/get/cuCmzXKUOa?indent=2"]]];

     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.json-generator.com/api/json/get/cpvIEMqesy?indent=2"]]];

    NSLog(@"%@",request);

    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (conn)
    {
        responseData = [[NSMutableData alloc] init];

    }else{

    }
}

Response Handling and parsing

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
    postresponce = [[NSMutableData alloc] init];
    [postresponce setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [responseData appendData:data];
    [postresponce appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    NSLog(@"%@ ", [error localizedDescription]);

}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSError *error=nil;

    NSDictionary *responCE =[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    respArray=[responCE valueForKey:@"yes_questions"];
   respArray1=[responCE valueForKey:@"no_questions"];



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

    [take5table reloadData];

}

Troublezone - Showing response in Tableview

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 2;

}

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

    switch (section) {
        case 0:
            return respArray.count;
            break;

        case 1:
            return respArray1.count;
            break;

        default:
            return 0;
    }
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

 [tableView deselectRowAtIndexPath:indexPath animated:YES];

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    NSLog(@"Section:%ld Row:%ld selected and its data is %@",
          (long)indexPath.section,(long)indexPath.row,cell.textLabel.text);
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

 if (section == 0) return @"First section header title";
    if (section == 1) return @"Second section header title";

    else

    return @"Hello World";
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier1";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    UILabel *Sno = (UILabel *)[cell viewWithTag:96];

    UILabel *QuesLab = (UILabel *)[cell viewWithTag:98];


    if (indexPath.section==0) {

     //   titleUIL.text = [[dicc valueForKey:[headersArray objectAtIndex:indexPath.section]]objectAtIndex:indexPath.row];

        Sno.text=[NSString stringWithFormat:@"%@",[[respArray objectAtIndex:indexPath.row] valueForKey:@"question_id"]];

        QuesLab.text=[[respArray objectAtIndex:indexPath.row]valueForKey:@"question_title"];

    }

    else if (indexPath.section==1){

        Sno.text=[NSString stringWithFormat:@"%@",[[respArray1 objectAtIndex:indexPath.row] valueForKey:@"question_id"]];

        QuesLab.text=[[respArray1 objectAtIndex:indexPath.row]valueForKey:@"question_title"];

    }

    if (indexPath.row %2 ==1)
        cell.backgroundColor = [UIColor colorWithRed:.9 green:.9 blue:.9 alpha:1];
    else
        cell.backgroundColor = [UIColor colorWithRed:.8 green:.8 blue:.8 alpha:1];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  50;
}

Error

-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x7f90d3eaf8a0
2016-11-08 10:44:16.935 Ecs Services[3691:701820] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x7f90d3eaf8a0'

My response is:

Printing description of responCE:
{
    "job_location" = "Crown Promenade ";
    "job_name" = "Test Schedule 2 for Crown Promenade";
    "job_no" = 207;
    "no_questions" =     {
        12 =         {
            "question_answer" = No;
            "question_id" = 13;
            "question_title" = "Is there a risk of falls or falling objects?";
            "question_type" = Full;
        };
        13 =         {
            "question_answer" = No;
            "question_id" = 14;
            "question_title" = "Is there a risk of Plant or Traffic interaction?";
            "question_type" = Full;
        };
        14 =         {
            "question_answer" = No;
            "question_id" = 15;
            "question_title" = " Is there a risk of electrical hazards?";
            "question_type" = Full;
        };
        15 =         {
            "question_answer" = No;
            "question_id" = 16;
            "question_title" = " Is the work in or involve a confined space? ";
            "question_type" = Full;
        };
        16 =         {
            "question_answer" = No;
            "question_id" = 19;
            "question_title" = " Does the job involve hot works?";
            "question_type" = Short;
        };
        17 =         {
            "question_answer" = No;
            "question_id" = 20;
            "question_title" = "Is there a risk of environmental damage? ";
            "question_type" = Full;
        };
        18 =         {
            "question_answer" = No;
            "question_id" = 21;
            "question_title" = " Is there a risk of crush injuries? (in,on or between)";
            "question_type" = Full;
        };
        19 =         {
            "question_answer" = No;
            "question_id" = 22;
            "question_title" = "Is there a risk of water  or sun hazards?";
            "question_type" = Full;
        };
        20 =         {
            "question_answer" = No;
            "question_id" = 23;
            "question_title" = "Are there any access issues or concerns ";
            "question_type" = Full;
        };
        21 =         {
            "question_answer" = No;
            "question_id" = 24;
            "question_title" = " Are there hazards involving unstable ground?";
            "question_type" = Full;
        };
        22 =         {
            "question_answer" = No;
            "question_id" = 25;
            "question_title" = " Do I need to apply isolation ?.................... ";
            "question_type" = Short;
        };
        23 =         {
            "question_answer" = No;
            "question_id" = 26;
            "question_title" = "Could there be any uncontrolled movement? \U2026...\U2026\U2026.\U2026.. ";
            "question_type" = Full;
        };
        24 =         {
            "question_answer" = No;
            "question_id" = 27;
            "question_title" = "Do I need mechanical lifting or a work at height platform? .. ";
            "question_type" = Full;
        };
        25 =         {
            "question_answer" = No;
            "question_id" = 39;
            "question_title" = test;
            "question_type" = Full;
        };
    };
    "yes_questions" =     {
        0 =         {
            "question_answer" = Yes;
            "question_id" = 1;
            "question_title" = " Do I understand the job thoroughly?";
            "question_type" = Full;
        };
        1 =         {
            "question_answer" = Yes;
            "question_id" = 2;
            "question_title" = "Am I authorized, qualified & trained to do the work?";
            "question_type" = Short;
        };
        10 =         {
            "question_answer" = Yes;
            "question_id" = 11;
            "question_title" = "Do I have the appropriate PPE & in good condition?";
            "question_type" = Full;
        };
        11 =         {
            "question_answer" = Yes;
            "question_id" = 12;
            "question_title" = "Can I complete the task on my own ? ";
            "question_type" = Full;
        };
        2 =         {
            "question_answer" = Yes;
            "question_id" = 3;
            "question_title" = "Do I have the correct tools & they\U2019re in good condition?";
            "question_type" = Full;
        };
        26 =         {
            "question_answer" = Yes;
            "question_id" = 40;
            "question_title" = "";
            "question_type" = Full;
        };
        27 =         {
            "question_answer" = Yes;
            "question_id" = 41;
            "question_title" = "equipment in good condition";
            "question_type" = Full;
        };
        3 =         {
            "question_answer" = Yes;
            "question_id" = 4;
            "question_title" = "Have I informed others who may be affected by my work? ";
            "question_type" = Full;
        };
        4 =         {
            "question_answer" = Yes;
            "question_id" = 5;
            "question_title" = "Is there free access to others not involved in the vicinity?";
            "question_type" = Full;
        };
        5 =         {
            "question_answer" = Yes;
            "question_id" = 6;
            "question_title" = " I have read & understand the SWMS applicable to this task? ";
            "question_type" = Full;
        };
        6 =         {
            "question_answer" = Yes;
            "question_id" = 7;
            "question_title" = "Have I obtained all permits & filled out correct paperwork? ";
            "question_type" = Short;
        };
        7 =         {
            "question_answer" = Yes;
            "question_id" = 8;
            "question_title" = "Have I applied lock out tags (where & if required)? ";
            "question_type" = Full;
        };
        8 =         {
            "question_answer" = Yes;
            "question_id" = 9;
            "question_title" = " Have I performed a pre job on-site inspection?";
            "question_type" = Full;
        };
        9 =         {
            "question_answer" = Yes;
            "question_id" = 10;
            "question_title" = " Am I fit for this task? (fatigue, injury, medications)";
            "question_type" = Full;
        };
    };
}
NSNoob
  • 5,548
  • 6
  • 41
  • 54
  • see this http://stackoverflow.com/questions/16521692/nscfdictionary-objectatindex-unrecognized-selector-sent-to-instance-0x894 – Anbu.Karthik Nov 08 '16 at 11:05
  • In the response you are getting `dictionary` not array. Thats why you are facing this issue. Either get the correct `array` from response or ask you web developer to update the response as desired. – pkc456 Nov 08 '16 at 11:06
  • You could have copy/pasted your code here, it would have been clearer (colored, etc.) and which is line is causing the issue exactly? Do we need the code for `numberOfSectionsInTableView:`? Doesn't seem relevant. Your issue `unrecognizedSelector sent to instance` is a well know issue. You are using a `NS(Mutable)Array` method on a `NSDictionary` object. My guess is that either `respArray` or `respArray1` is not a `NSArray` as you think it is. – Larme Nov 08 '16 at 11:12
  • getting error in the below lines Sno.text=[NSString stringWithFormat:@"%@",[[respArray objectAtIndex:indexPath.row] valueForKey:@"question_id"]]; QuesLab.text=[[respArray objectAtIndex:indexPath.row]valueForKey:@"question_title"]; @Larme –  Nov 08 '16 at 11:20
  • Anyways, the issue could be anywhere in your `cellForRowAtIndexPath` where you access indexPath.row to extract elements from what you have assumed is an array but it actually is a dictionary. Put exception breakpoints, see what it is and figure out what has proved your assumption false. – NSNoob Nov 08 '16 at 11:21
  • Sno.text=[NSString stringWithFormat:@"%@",[[respArray objectAtIndex:indexPath.row] valueForKey:@"question_id"]]; QuesLab.text=[[respArray objectAtIndex:indexPath.row]valueForKey:@"question_title"]; getting error here. @NSNoob –  Nov 08 '16 at 11:22
  • @pegallapatipurushotham That's what I said. What is your response structure? The issue is evident, at some point, `respArray=[responCE valueForKey:@"yes_questions"];` gives you a dictionary instead of an array. That causes the crash. – NSNoob Nov 08 '16 at 11:23
  • my responCE result is : http://pastie.org/10957914 , can u suggest me how to write nsdictionary @NSNoob –  Nov 08 '16 at 11:27
  • Yup your response is returning you a dictionary for both yes and no questions. Those dictionaries contain dictionaries inside them. Contrary to what you believe, you aren't getting an array of dictionaries. – NSNoob Nov 08 '16 at 11:37
  • can u tell me , how to implement that dictionary in the cellForRowAtIndexPath @NSNoob –  Nov 08 '16 at 11:38

1 Answers1

0

The problem is, your response is returning you dictionaries, not arrays as you are expecting. To fix that, you can use the allValues method of NSDictionary which returns you an array of all values inside a dictionary.

To fix that, make following corrections:

In your response parsing:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSError *error=nil;

    NSDictionary *responCE =[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    respArray=[[responCE valueForKey:@"yes_questions"] allValues]; //Now you have array of dictionaries which were contained in the dictionary with key yes_question
   respArray1=[[responCE valueForKey:@"no_questions"] allValues];//Now you have array of dictionaries which were contained in the dictionary with key no_question



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

    [take5table reloadData];

}
NSNoob
  • 5,548
  • 6
  • 41
  • 54
  • it working fine , but it is not displaying in the sequentially, can u tell me , how to do ? –  Nov 08 '16 at 12:09
  • Pegallapati, That's because NSDictionary is always unordered. So when you call allValues method, you can't predict the order. You can use allKeys method of NSDictionary to get all keys, sort the resultant array and then use that sorted array of keys to extract objects from your NSDictionary sequentially. – NSNoob Nov 08 '16 at 12:11
  • oh thanks a lot ! , if u give sample code , i ll be very thankful to u , –  Nov 08 '16 at 12:14
  • [See my previous answer here](http://stackoverflow.com/questions/35934284/nsdictionary-getting-sorted-alphabetically/35934385#35934385) . – NSNoob Nov 08 '16 at 12:22