我正在尝试检索id
的价值:
{"id":1,"name":"XYZ"}
当我使用时:
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
NSArray * myPeople = [jsonData JSONValue];
NSString *name = [[NSString alloc] init];
NSDictionary *person = [myPeople objectAtIndex:[indexPath row]];
name = [NSString stringWithString:[person valueForKey:@"id"]];
name = [name stringByAppendingString:@". "];
name = [name stringByAppendingString:[person valueForKey:@"name"]];
name = [name stringByAppendingString:[person valueForKey:@"id"]];
cell.textLabel.text = name;
我收到以下错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException'
reason: '-[NSCFNumber length]: unrecognized selector sent to instance 0x4e7f8b0
我该如何解决这个问题?
答案 0 :(得分:8)
您同时拨打stringWithString:
和stringByAppendingString:
,但随后传入NSNumber
您需要获取NSNumber
[[person valueForKey:@"id"] stringValue];
或使用如下格式:
name = [NSString stringWithFormat:@"%@%@", name, [person valueForKey:@"id"]];
我还会考虑稍微改变结构,以便更容易遵循:
NSDictionary *person = [myPeople objectAtIndex:[indexPath row]];
NSString *personName = [person valueForKey:@"name"];
NSSNumber *personId = [person valueForKey:@"id"];
NSString *name = [NSString stringWithFormat:@"%@. %@ %@", personId, personName, personId];
对于排序,您希望确保每次设置单元格时都不会提取数据(看起来像你),否则这将是一次糟糕的体验。
我相信有人可以指出你更好的排序方式,但我能想到的最快的事情是
NSArray *myPeople = [[jsonData JSONValue] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[obj1 objectForKey:@"id"] compare:[obj2 objectForKey:@"id"]];
}]