我有一组 Videos
对象,其中包括属性 id
和 tags
。
我想建立一个字典,它的 key
是一个 tag
而它的 value
是一个 id
的数组的。
例如,某些 Video
对象可能如下所示:
Video{ id:1, tags:[搞笑,政治,幽默] }
视频{ id:2, tags:[political,america] }
我希望结果字典看起来像这样:
VideosWithTags["搞笑":[1]; “政治”:[1,2]; “幽默”:[1]; “美国”:[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];
}
}
}
最佳答案
您可以使用新的文字语法使它看起来更简洁一些。
我认为您可以通过减少 if
分支的工作量来获益。例如您最好尝试检索 videoIds
数组,如果它不存在 - 创建它并将其添加到 videosAndTags
对象,然后此点之后的代码可以保持一致,不重复逻辑
for (NSDictionary *video in videos) {
NSNumber *videoId = video[@"id"];
NSArray *tags = video[@"tags"];
for (NSString *tag in tags) {
NSMutableArray *videoIds = videosAndTags[tag];
if (!videoIds) {
videoIds = [NSMutableArray array];
videosAndTags[tag] = videoIds;
}
// This is the only line where I manipulate the array
[videoIds addObject:videoId];
}
}
关于objective-c - 建立一对多关系的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15952599/