Search code examples
iosobjective-carraysjsonnsarray

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance


I'm trying to alter the following array like this. Actual Response:

 errFlag = 0;
    errMsg = "Got Slot successfully.";
    errNum = 128;
    slots =     (
                {
            date = "";
            slot =             (
                                {
                    booked = 1;
                    end = 1510822800;
                    "end_dt" = "09:00:00";
                    id = 5a02a0372279511b1c968a10;
                    locId = "";
                    radius = 1;
                    "slot_price" = 20;
                    start = 1510815600;
                    "start_dt" = "07:00:00";
                }
            );
        }
    );

The response I want it like...

{
 "start_dt" = "07:00:00";
                    }
{
 "start_dt" = "11:00:00";
                    }
{
 "start_dt" = "14:00:00";
                    }

I Attempted this on following way but I ended up with an excemption.

if (requestType == RequestTypeGetAllMetSlots)
        {

            // altering the response into an array
            NSDictionary *slotResultsDict = response[@"slots"];
            NSLog(@"Priniting timeSlotResponseDict%@",slotResultsDict);
            timeSlotResponseArray = [[slotResultsDict objectForKey:@"slot"] valueForKey:@"start_dt"];
            NSLog(@"Priniting timeSlotResponseArray%@",timeSlotResponseArray);


        }

Following is the Exeception I got.. Please help me..

 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance

Solution

  • Crashing because response is an array not dictionary. And slot is also an array not dictionary.

    Try this.

    NSArray *slots = response[@"slots"]
    NSDictionary *slotResultsDict = [slots firstObject];
    NSLog(@"Priniting timeSlotResponseDict%@",slotResultsDict);
    
    NSDictionary *subSlot = [[slotResultsDict objectForKey:@"slot"] firstObject];
    timeSlotResponseArray = [subSlot valueForKey:@"start_dt"];
    NSLog(@"Priniting timeSlotResponseArray%@",timeSlotResponseArray);
    

    Or in one line.

    NSString *startDate = [[[[response[@"slots"] firstObject] objectForKey:@"slot"] firstObject] objectForKey:@"start_dt"];