1

我使用Parse作为我的后端服务,但是对于这个示例,我创建了两个示例数组 (songsratings) 来模仿我的后端架构。songs包含将填充我的应用程序表的歌曲数据。ratings包括当前用户对歌曲的评分。

最终,我需要遍历songs并将ratings其嵌入到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"];
    }
4

1 回答 1

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"];
}
于 2012-09-13T00:10:24.117 回答