Consider this...
A game has players. Each player in the game achieves a score. Whether they win or lose depends on their score compared to the other player's score for that game.
My suggestion...
- Entity:
Player
- Attribute:
NSString *name
- Relationship:
playerGames
one-to-many Game
- Entity:
Game
- Attribute:
NSString *reference
(e.g. Game "1")
- Attribute:
NSNumber *scorePlayer1
- Attribute:
NSNumber *scorePlayer2
- (Attribute:
NSDate *timeStamp
) option?
- Relationship:
gamePlayer1
many-to-one Player
- Relationship:
gamePlayer2
many-to-one Player
(where player 2 cannot equal player 1)
So then we can have...
Game *game = [[Game alloc] init...];
if (game.scorePlayer1 > game.scorePlayer2) {
NSLog("%@ is winner and %@ is loser with score %@-%@", game.gamePlayer1.name, gamePlayer2.name, scorePlayer1, scorePlayer2);
} else if (game.scorePlayer2 > game.scorePlayer1) {
NSLog("%@ is winner and %@ is loser with score %@-%@", game.gamePlayer2.name, gamePlayer1.name, scorePlayer2, scorePlayer1);
} else {
NSLog("Players %@ and %@ drew with score %@-%@", game.gamePlayer1.name, gamePlayer2.name, scorePlayer1, scorePlayer2);
}
Player *player = [[Player alloc] init...];
NSFetchRequest *requestWins = [[NSFetchRequest alloc] initWithEntity:@"Game"];
NSPredicate *predicateAsPlayer1 = [NSPredicate predicateWithFormat: @"(%@ >= %@) && (game.gamePlayer1.name == %@)", game.scorePlayer1, game.scorePlayer2, player];
NSPredicate *predicateAsPlayer2 = [NSPredicate predicateWithFormat: @"(%@ >= %@) && (game.gamePlayer2.name == %@)", game.scorePlayer2, game.scorePlayer1, player];
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicateAsPlayer1, predicateAsPlayer2]];
[requestWins setPredicate:predicate];
NSArray *arrayWins = [managedObjectContext executeFetchRequest:requestWins];
NSFetchRequest *requestLosses = [[NSFetchRequest alloc] initWithEntity:@"Game"];
...<repeat similar to above>...
NSArray *arrayLosses = [managedObjectContext executeFetchRequest:requestLosses];
NSInteger gamesPlayed = player.playerGames.count;
NSInteger gamesWon = arrayWins.count;
NSInteger gamesLost = arrayLosses.count;
NSInteger gamesDrawn = gamesPlayed - gamesWon - gamesLost;
Hope this helps.