我有一组Videos
对象,其中包括属性id
和tags
.
我想建立一个字典,它key
是一个tag
并且value
是一个数组id
。
例如,某些Video
对象可能如下所示:
Video{ id:1, tags:[funny,political,humor] }
Video{ id:2, tags:[political,america] }
我希望结果字典看起来像这样:
VideosWithTags["funny":[1]; "political":[1,2]; "humor":[1]; "america":[2]]
有没有标准的算法来完成这个?
目前我正在做这样的事情:
for (NSDictionary *video in videos)
{
NSNumber *videoId = [video objectForKey:@"id"];
NSArray *tags = [video objectForKey:@"tags"];
for (NSString *tag in tags)
{
NSMutableArray *videoIdsForTag = nil;
if ([videosAndTags objectForKey:tag] != nil) //same tag with videoIds already exists
{
videoIdsForTag = [videosAndTags objectForKey:tag];
[videoIdsForTag addObject:videoId];
//add the updated array to the tag key
[videosAndTags setValue:videoIdsForTag forKey:tag];
}
else //tag doesn't exist yet, create it and add the videoId to a new array
{
NSMutableArray *videoIds = [NSMutableArray array];
[videoIds addObject:videoId];
//add the new array to the tag key
[videosAndTags setObject:videoIds forKey:tag];
}
}
}