iphone - Objective-C中的高效循环

标签 iphone objective-c ios loops

我将Parse用作后端服务,但是在本示例中,我创建了两个示例数组(songsratings)来模仿我的后端架构。 songs由将填充我的应用程序表的歌曲数据组成。 ratings由当前用户的歌曲评分组成。

最终,我需要遍历songsratings以将userRating嵌入各自的songs字典中。我在下面包含了我的循环代码。可以更有效地做到这一点吗?我担心如果有太多的ratings对象,它将花费太长时间。

    NSMutableArray *songs = [@[ @{
                                @"objectId" : @"111",
                                @"title" : @"Song Title" },
                                @{
                                @"objectId" : @"222",
                                @"title" : @"Song Title"
                             } ] mutableCopy];

    NSMutableArray *ratings = [@[ @{
                               @"objectId" : @"999",
                               @"parentObjectId" : @"111",
                               @"userRating" : @4
                               } ] mutableCopy];

    for (NSInteger a = 0; a < songs.count; a++) {

        NSMutableDictionary *songInfo = [songs objectAtIndex:a];
        NSString *songObjectId = [songInfo objectForKey:@"objectId"];
        NSNumber *userRating = @0;

        for (NSInteger i = 0; i < ratings.count; i++) {

            NSDictionary *userRatingInfo = [ratings objectAtIndex:i];
            NSString *parentObjectId = [userRatingInfo objectForKey:@"parentObjectId"];

            if ([parentObjectId isEqualToString:songObjectId]) {
                userRating = [userRatingInfo objectForKey:@"userRating"];
            }
        }
    [songInfo setObject:userRating forKey:@"userRating"];
    }

最佳答案

建立评级字典,而不要有内在循环。您的时间复杂度将从n * m变为n + m,因为字典查找将分摊固定时间:

NSMutableDictionary* ratingsDict = [NSMutableDictionary dictionaryWithCapacity:ratings.count];
for (NSDictionary* rating in ratings) {
    NSString *parentObjectId = [rating objectForKey:@"parentObjectId"];
    [ratingsDict setObject:rating forKey:parentObjectId];
}

for (NSMutableDictionary* song in songs) {
    NSString *songObjectId = [song objectForKey:@"objectId"];
    NSNumber *userRating = [ratingsDict objectForKey:songObjectId];
    if (userRating)
        [song setObject:userRating forKey:@"userRating"];
}

关于iphone - Objective-C中的高效循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12397483/

相关文章:

iphone - 将 iphone 应用程序从 xcode 部署到 iphone

iphone - 如何在表格 View 的第一部分中显示数组的第一项,并在下一部分中显示剩余项?

iphone - bundle 访问中的sqlite db路径?

iphone - 如何使用 iPhone SDK 改变图像的形状?

ios - 如何在Xcode 7.3的控制台中访问“ self ”

ios - 从非 ECSlidingViewController 打开 ECSlidingViewController

ios - Swift 3 : How do I increase a variable being displayed as a UILabel, 然后以编程方式更新 UILabel?

ios - MBProgressHUD 添加到 navigationController.view 而不禁用 userInteraction

objective-c - 如何在 iPad 中添加如图所示的 strip ?

iOS 不平衡调用 applicationWillResignActive : and applicationDidBecomeActive: