1

I am trying to replace objects in a many to one ordered CoreData relationship... My code is here:

NSMutableOrderedSet *battingLineUpTemp = [battingOrderToChange.battingOrder mutableCopy];
    NSUInteger newBatsmanIndex = 0;

NSLog(@"Original batting order");
for (CricketPlayer *p in battingLineUpTemp) {
    NSLog(@"switching : %@ %@",p.firstName, p.lastName);
}

for (int i = [innings.wicketsFallen integerValue] +2; i < [battingOrderToChange.battingOrder count]; i++) {

    //[battingLineUpTemp replaceObjectAtIndex:i withObject:batsmenArray[newBatsmanIndex]];
    [battingLineUpTemp replaceObjectAtIndex:i withObject:[batsmenArray objectAtIndex:newBatsmanIndex]];
    newBatsmanIndex++;

}

NSLog(@"Changed batting order");
for (CricketPlayer *p in battingLineUpTemp) {
    NSLog(@"switching : %@ %@",p.firstName, p.lastName);
}


[battingOrderToChange willChangeValueForKey:@"battingOrder"];
[battingOrderToChange setBattingOrder:[[NSOrderedSet alloc] initWithOrderedSet:[battingLineUpTemp copy]]];
battingOrderToChange.battingOrder = battingLineUpTemp;
[battingOrderToChange didChangeValueForKey:@"battingOrder"];

Yet the second time i output the players names I get the exact same result as beforehand! I have made sure that the NSArray (batsmenArray) which I'm passing to the method is not in the same order as *battingLineUpTemp... Why is my code refusing to let me change the order of this NSMutableOrderedSet!? Is it CoreData being a massive pain in the arse once again?

Edit 1 I have also made sure that the object that I am replacing and the one which it is replacing are different by NSLogging within the for loop... the NSMutableOrderedSet is simply refusing to be rearranged!

simonthumper
  • 1,834
  • 2
  • 22
  • 44

1 Answers1

0

SimonThumper,

An ordered set has many uses, but it is primarily a mechanism to preserve insertion order. As you want to change your lineup order, I suggest you actually add a property to contain the position in the lineup and then sort on that order. (You could also use this as a property to easily pull the lineup out of the roster by checking for non-zero values in the lineup property.)

Andrew

adonoho
  • 4,339
  • 1
  • 18
  • 22
  • 1
    This kind-of-answered my problem so thank you very much! Instead of adding another property to contain the position, I simply changed battingLineUpTemp to an NSMutableArray and added each player from battingOrderToChange.battingOrder to it within a loop... I then reordered that NSMutableArray and set the CoreData attribute by initing an NSOrderedSet using the method `orderedSetWithArray:` – simonthumper Jun 24 '13 at 17:38
  • Glad I could help. As it appears I answered your question, would you mind accepting this answer by selecting the green checkmark? Thank you and Continued Luck with your project, Andrew – adonoho Jun 25 '13 at 02:44
  • Sure thing, sorry for the delay! been busy! Simn – simonthumper Jun 25 '13 at 21:16