How to handle '[<__NSCFString 0x2f1730> valueForUndefinedKey:]: this class is not key value coding-compliant for the key $oid' error

一曲冷凌霜 提交于 2019-12-08 01:32:22

问题


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?


回答1:


Try the following code.

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



回答2:


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.



来源:https://stackoverflow.com/questions/8754860/how-to-handle-nscfstring-0x2f1730-valueforundefinedkey-this-class-is-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!