我将Parse用作后端服务,但是在本示例中,我创建了两个示例数组(songs
和ratings
)来模仿我的后端架构。 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"];
}
最佳答案
建立评级字典,而不要有内在循环。您的时间复杂度将从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/