objective-c - 建立一对多关系的最佳方式是什么?

标签 objective-c performance algorithm

我有一组 Videos 对象,其中包括属性 idtags

我想建立一个字典,它的 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/

相关文章:

java - Prim的迷宫生成算法: Getting the neighbour cell

ios - 有什么方法可以阻止 UIImageView 中的图像在 iOS 上使用 SDWebImage 延迟加载?

ios - 我将如何开始复制 Apple 在 iOS 7 中作为默认设置使用的自定义 View Controller 转换?

ios - 缩放 UIView 及其所有子项

python - 查找二维数组每列最后一个非零值的索引

algorithm - [a;b] 段有多少个不吉利的数字?

objective-c - 在 Swift 中访问 object-c NSDictionary 值很慢

c# - 在 .NET 中如何最有效地利用多核进行短计算?

performance - 覆盖使 emacs 真的很慢

algorithm - 证明 NP-Completeness clique + 独立集图