我有一个来自 json 的 nsdictionary,它响应:
({
email = "something@gmail.com";
name = "User1";
},
{
email = "something2@gmail.com";
name = "user2";
})
这是我在 de .m 文件中的代码:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
int errorCode = httpResponse.statusCode;
NSString *fileMIMEType = [[httpResponse MIMEType] lowercaseString];
NSLog(@"response is %d, %@", errorCode, fileMIMEType);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//NSLog(@"data is %@", data);
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(@"string is %@", myString);
NSError *e = nil;
usersDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSLog(@"dictionary is %@", usersDictionary);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// inform the user
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NombreUsuario = [[NSMutableArray alloc] initWithCapacity:[usersDictionary count]];
}
我用它来返回部分中的行数:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [usersDictionary count];
}
但我不知道如何将数据电子邮件、名称对放入表格 View 中,其中每个单元格都必须显示名称的主标签和电子邮件的副标题。
提前致谢。
最佳答案
我会回答我自己的问题,以供将来可能需要的人引用。
首先,我必须将 json 响应存储在 NSMutableArray 而不是字典中。
因为我有一个字典数组,所以我有两个级别的信息,我试图将它分解成新的对象,但这不是正确的方法,所以要访问第二个级别我必须导航到它:
cell.textLabel.text = [[NombreUsuario objectAtIndex:indexPath.row]objectForKey:@"name"];
使用 [NombreUsuario objectAtIndex:indexPath.row] 我访问了第一级信息,然后使用 objectForKey:@"name"我获得了与键“name”匹配的所有值。
对于详细信息标签文本是相同的:
cell.detailTextLabel.text = [[NombreUsuario objectAtIndex:indexPath.row]objectForKey:@"email"];
感谢大家的帮助。
关于ios - 从 nsdictionary 填充 uitableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19465796/