在objective-c中有效循环

时间:2012-09-12 23:36:01

标签: 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"];
    }

1 个答案:

答案 0 :(得分:3)

建立一个评级字典而不是内循环。您的时间复杂度将从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"];
}