I have the following
// this code is inside cellForRowAtIndexPath for a TableViewController
id answer = [self.answers objectAtIndex:indexPath.row];
if ([answer respondsToSelector:@selector(objectForKey)]) {
cell.textLabel.text = [answer valueForKey:@"answer_id"];
} else {
// I'm ending up here, instead of the cell.textLabel being set
[NSException raise:@"Answer is of invalid class" format:@"It should be able to respond to valueForKey, class: %@", [answer class]];
}
where self.answers is set to
// the question that gets passed here is a parsed single object
// from the `/questions` path
- (NSArray *)answersForQuestion:(NSDictionary *)question {
NSString *contents = [self loadContentsForPath:[question valueForKey:@"question_answers_url"]];
valueForKey:@"question_answers_url"]];
NSDictionary *data = [contents JSONValue];
NSArray *answers = [data valueForKey:@"answers"];
return answers;
}
- (NSString *)loadContentsForPath:(NSString *)path {
NSString *wholeURL = [@"http://api.stackoverflow.com/1.1" stringByAppendingString:path];
return [NSString stringWithContentsOfURL:[NSURL URLWithString:wholeURL] encoding:NSUTF8StringEncoding error:nil];
}
I’m doing exactly the same thing for loading questions which works just fine, but it seems
to fail on answers when I try to do [answers valueForKey:@"answer_id"].
I don’t think this is a problem with the JSON parser, because it works fine for the /questions data.
When the debugger stops on the exception and when I try to right click -> Print Description on answers, I get
Printing description of answer:
<CFBasicHash 0x6ec1ec0 [0x1474b38]>{type = mutable dict, count = 13,
entries =>
1 : <CFString 0x6ec57d0 [0x1474b38]>{contents = "down_vote_count"} = <CFNumber 0x6e1dc00 [0x1474b38]>{value = +0, type = kCFNumberSInt32Type}
2 : <CFString 0x6ec4ee0 [0x1474b38]>{contents = "last_activity_date"} = <CFNumber 0x6ec5780 [0x1474b38]>{value = +1326379080, type = kCFNumberSInt64Type}
3 : <CFString 0x6ec44b0 [0x1474b38]>{contents = "community_owned"} = <CFBoolean 0x1474f68 [0x1474b38]>{value = false}
...
which to me seems like a regular hash. I tried both objectForKey and valueForKey and neither of them work, i.e.
exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x6b2a330'
when I do just
cell.textLabel.text = [answer objectForKey:@"answer_id"];
The
:is a part of the method name, so you need to do:And then use
objectForKey:, notvalueForKey:. The first is to access objects in the dictionary, the later is for the so-called Key-Value Coding. So it’s:Last but not least, it looks like the object you get out of the
answerdictionary is aNSNumber, not anNSString. So you might want to change the setting of the text to: