开发者

NSDictionary within NSArray

A quick question about NSArrays and NDictionarys.

I have and NSArray containing NSDictionarys. The NSDictionary contain a date and开发者_JAVA百科 a string.

What I would like to do is end up with an NSDictionary with keys dates and values arrays of strings that are on that date.

What would be the best way to do this


NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSDictionary *dict in array) {
    NSDate *date = [dict objectForKey:@"dateKey"];
    NSString *string = [dict objectForKey:@"stringKey"];
    NSMutableArray *stringsWithDate = [result objectForKey:date];
    if (!stringsWithDate) {
        stringsWithDate = [NSMutableArray array];
        [result setObject:stringsWithDate forKey:date];
    }
    [stringsWithDate addObject:string];
}

Note that NSDate is not a "calendar date", so the same day with a different time will be considered as a distinct date in your result dictionary.


As I do not see any reasonable motivation for doing this, let's call it code golf.

NSMutableArray *dates = [NSMutableArray array];
NSMutableArray *strings = [NSMutableArray array];

for (NSDictionary *dict in dictArray) {
    [dates addObject:[dict objectForKey:@"date"]];
    [strings addObject:[dict objectForKey:@"string"]];
}

NSArray *datesArray = [[NSArray alloc] initWithArray:dates];
NSArray *stringsArray = [[NSArray alloc] initWithArray:strings];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜