So I got entities Level and Tile. Level has a to-many relationship with Tile. Tile has a property 'index'.
Right now I'm using this code to get the tiles array of Level sorted:
- (NSArray *)sortedTiles
{
NSMutableArray *sortedTiles = [NSMutableArray arrayWithArray:[self.tiles allObjects]];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"index" ascending:YES];
[sortedTiles sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
return sortedTiles;
}
This works, but I want to be able to retrieve a single Tile with a certain index, so I wrote this method in Level.h:
- (Tile *)tileWithIndex:(NSInteger)index;
The implementation is fairly simple:
- (Tile *)tileWithIndex:(NSInteger)index
{
NSArray *sortedTiles = [self sortedTiles];
Tile *tile = [sortedTiles objectAtIndex:index];
return tile;
}
Now, ofcourse this isn't the most efficient way in doing so because the tiles array has to be allocated and sorted each time, so I was thinking: if I just add an instance variable to Level, 'sortedTiles', then I won't have to rebuild it each time. But Level is a subclass of NSManagedObject, so is this possible and/or wise to do?