我是iOS开发的新手,我的问题是当我解析数据时,只显示上面显示的值的上一个值没有显示。请解决我的问题。 数组名称city info获取3个值,但是当我想显示它们时,它给出了数组的最后一个值。
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:WebData1 options:0 error:0];
NSArray *city_info = [json objectForKey:@"city_info"];
for(NSDictionary *dic in city_info) {
NSMutableArray *vlcc_service_name = [dic objectForKey:@"vlcc_service_name"];
Centers = [[NSMutableArray alloc]initWithObjects:vlcc_service_name, nil];
}
// NSLog(@"%@", vlcc_service_name);
NSLog(@"%@", Centers);
[_CenterTableView reloadData];
}
答案 0 :(得分:4)
NSDictionaries是无序的,没有第一个或最后一个元素。实际上,即使在特定字典的生命周期内,密钥的顺序也永远不会保证是相同的。
如果您想要任何对象,可以获得其中一个键:
var country = "Please click on a country";
function setCountry(event) {
country = this.id;
return false;
}
function search_track() {
// do something with country, such as:
alert(country);
}
document.getElementById("canada").addEventListener("click", setCountry, false);
document.getElementById("usa").addEventListener("click", setCountry, false);
document.getElementById("search_track").addEventListener("click", search_track, false);
选择 - 2
数组你可以获得所有对象
id key = [[json allKeys] objectAtIndex:0]; // ensure that your 'json' is not empty
id object = [json objectForKey:key];
答案 1 :(得分:0)
Centers = [NSMutableArray new]; // allocate the memory on outside the Loop
for(NSDictionary *dic in city_info) {
[Centers addObject: [dic objectForKey:@"vlcc_service_name"]];
}
NSLog(@"the last object=%@", [Centers lastObject]);
// else
NSLog(@"the last object=%@", [yourArray objectAtIndex:[Centers count] - 1]; );
答案 2 :(得分:0)
您可以在没有任何for loop
的情况下执行此操作。这样做:
NSMutableArray *Centers = [[NSMutableArray alloc]initwithArray:city_info];
答案 3 :(得分:0)
请试试这个。
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:WebData1 options:0 error:0];
NSArray *city_info = [json objectForKey:@"city_info"];
NSMutableArray *Centers = [[NSMutableArray alloc]init];
for(NSDictionary *dic in city_info) {
NSString *vlcc_service_name = [dic objectForKey:@"vlcc_service_name"];
/NSLog(@"%@", vlcc_service_name);
[Centers addObject: vlcc_service_name];
}
NSLog(@"%@", Centers);
[_CenterTableView reloadData];
}