我正在获取如下数据,我希望得到像names= app,app1,app2
这样的数据而不需要循环。如果没有循环,我能实现这个吗?
(
{
date = "12/12/12";
name = app;
},
{
date = "11/02/12";
name = app1;
},
{
date = "14/05/12";
name = app2;
}
)
答案 0 :(得分:6)
是的。可以尝试这样做。不需要在这里采用任何循环概念这个在有大量数据时非常有用。
NSString *str=[[array1 valueForKeyPath:@"name"] componentsJoinedByString:@","];
NSLog(@"desired string:%@",str);
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:@"app" forKey:@"name"];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc]init];
[dict1 setObject:@"app1" forKey:@"name"];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
[dict2 setObject:@"app2" forKey:@"name"];
NSArray *array1 = [[NSArray alloc]initWithObjects:dict,dict1,dict2, nil];
NSString *str=[[array1 valueForKeyPath:@"name"] componentsJoinedByString:@","];
NSLog(@"desired string:%@",str);
O/P:- app,app1,app2
答案 1 :(得分:5)
NSArray * yourArray = @[
@{
@"date" : @"12/12/12",
@"name" : @"app"
},
@{
@"date" : @"11/02/12",
@"name" : @"app1"
},
@{
@"date" : @"14/05/12",
@"name" : @"app2"
}
];
NSArray * selectedArray = [yourArray valueForKeyPath:@"@distinctUnionOfObjects.name"];
NSArray * sortedArray = [selectedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];
}];
NSString * str = [NSString stringWithFormat:@"name=%@",[sortedArray componentsJoinedByString:@","]];
NSLog(@"%@",str);