I have a class that manages cells in a grid.
I am trying to decide if I should store the cells of the grid in a NSArray or NSDictionary.
NSArray: Given a position, it generates an index to look the cell up in an Array
Advantage: speed
Disadvantage: sorta clunky code where I have to manage the index.
If I stored them in an NSArray the code would look like:
Code:
- (PathNode *)nodeAtPosition: (CGPoint) position;
{
// Test to see if we are asking for a position that is out of bounds
if( position.x > (self.height-1) || position.y > (self.width-1) || position.x < 0 || position.y < 0)
return nil;
int index = (position.x * self.height + position.y);
return [self.pathNodes objectAtIndex:index];
}
NSDictionary: the Key for the NSDictionary is a custom class that wraps up a CGPoint
Advantage: Nice clean code and the lifting is done by apple (NSDictionary)
Disadvantage: Possibly slower, and it looks like keys are stored as memory location instead of by value. I believe I must implement a isEqual and a hash method, but I am not too sure how.
Code:
- (PathNode *)nodeAtPosition: (CGPoint) position;
{
// Create a new JBPoint
JBPoint *JBPosition = [[JBPoint alloc] initWithPosition:position];
// Get the object at the position
PathNode *pathNodeAtPosition = [[self.pathNodesDict objectForKey:JBPosition] retain];
// Release the JBPoint
[JBPosition release];
[pathNodeAtPosition autorelease];
// No need to error check if the position is valid. If it is not valid nil is returned
return pathNodeAtPosition;
}
Do you think a dictionary solution would be substantially slower?
Also, if you think the dictionary route is the best can you think of a good way to implement the hash: method?
The isEqual is easy:
Code:
- (BOOL)isEqual:(JBPoint *)anObject
{
//NSLog(@"JBPoint equality Test %d, %d; %d, %d", anObject.x, self.x, anObject.y, self.y);
if( anObject.x == self.x && anObject.y == self.y )
{
return YES;
}
return NO;
}
Thanks for any help,
Jacob