2

I am hitting the error (stated in the subject) because there are times the property 'id' does not store the hash containing '$oid' in the returned json. For example

Sometimes I get:

"id":{"$oid":"4eea972209f47a0028000140"}

Some other times I get

"id":"4eea972209f47a0028000140"

I am trying to do a check in the following code to cater for such irregularity

if ([[question valueForKey:@"id"] valueForKey:@"$oid"])
{
    question_id = [[question valueForKey:@"id"] valueForKey:@"$oid"];
}
else
{
    question_id = [question valueForKey:@"id"];
}

However, it still doesn't work as the code fails during the checking phase.

How can I implement a check so that I will take question_id from '$oid' only if it exists?

Zhen
  • 12,361
  • 38
  • 122
  • 199

2 Answers2

5

Try the following code.

id quesDict = [question valueForKey:@"id"];
if( [quesDict isKindOfClass:[NSDictionary class]] )
{
    question_id = [quesDict valueForKey:@"$oid"];
}
else
{
    question_id = quesDict;
}
Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
3

You need to check what type is being returned by [question valueForKey:@"id"], it looks like sometimes it is a string, and sometimes it is another object which is KVC compliant for your other key. Your error will be in the very first if statement.

jrturton
  • 118,105
  • 32
  • 252
  • 268