Properly maintain sorted state of Array/Set
Posted
by Jeff
on Stack Overflow
See other posts from Stack Overflow
or by Jeff
Published on 2010-04-20T04:04:21Z
Indexed on
2010/04/20
4:13 UTC
Read the original article
Hit count: 282
I'm trying to get data out of my MOC and then create some new objects based on those objects, and put it all back together, while keeping my sort state.
The securities come out of the MOC in proper order. And everything seems to be fine until I do the assignment to the game at the bottom from setWithArray. The documentation says that setWithArray removed the duplicate objects, if there are any. I'm wonder if that's messing up my data, but I don't see a good alternative.
The data is ultimately being pulled out into a UITableView. When I add items to the game manually, then they stay sorted, so I don't think the breaking of the sort is beyond the scope of what I've included here.
NSError *error;
NSArray *allTheSecurities = [managedObjectContext executeFetchRequest:request error:&error];
if (allTheSecurities == nil) {
// Handle the error.
}
[request release];
/**/
NSLog( @"Enumerate..." );
NSEnumerator *enumerator = [allTheSecurities objectEnumerator];
id anObject;
NSMutableArray *portfolioStocks = [[NSMutableArray alloc] init];
while (anObject = [enumerator nextObject]) {
NSLog( @"Iteration... %@", [anObject name] );
NSLog( @"Build a stock..." );
PortfolioStocks *this_stock = (PortfolioStocks *)[NSEntityDescription insertNewObjectForEntityForName:@"PortfolioStocks" inManagedObjectContext:context];
NSLog( @"Set a value..." );
[this_stock setSecurity:(Security *)anObject];
[this_stock setQuantity:[NSNumber numberWithInt:0]];
NSLog( @"Add to portfolioStocks..." );
[portfolioStocks addObject:this_stock];
}
//Sorted properly up to here!
NSLog( @"Add to portfolio..." );
[game setPortfolio:[NSSet setWithArray:portfolioStocks]]; // <-- This is where it's not sorted anymore.
© Stack Overflow or respective owner