在objective-c中循环有效

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

最终,我需要循环songsratings ,将userRatingembedded各自的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"]; } 

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