I’m using Parse as my backend service, but for this example I created two sample Arrays (songs and ratings) that mimic my backend schema. songs consists of song data that will populate my app’s table. ratings consist of the current user’s ratings of songs.
Ultimately, I need to loop through songs and ratings to embed the userRating in the respective songs dictionary. I’ve included my looping code below. Can this be done more efficiently? I’m worried it will take too long if there are too many ratings objects.
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 a dictionary of ratings instead of having an inner loop. Your time complexity will go from n*m to n+m since dictionary lookups are amortized constant time: