我有一組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];
}
}
}
這代碼看上去完全合理的我。你覺得有什麼需要改進的地方嗎?重構它會容易一點點,但它不會明顯改變性能。 – 2013-04-11 15:36:47
不是特別的,比任何事情都更好奇。 – 2013-04-11 15:44:33