Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Mockup & CodeGen, iPhone & iPad
($9.99)

Make your own iPhone apps
and run them live!
(free)

Manu
($0.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum

View Single Post
Old 05-07-2009, 04:07 AM   #1 (permalink)
jacobhb
New Member
 
Join Date: Apr 2009
Posts: 5
Default NSArray or NSDictionary to store grid cells

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

Last edited by jacobhb; 05-07-2009 at 09:11 PM.
jacobhb is offline   Reply With Quote
 

» Advertisements
» Stats
Members: 158,688
Threads: 89,160
Posts: 380,406
Top Poster: BrianSlick (7,110)
Welcome to our newest member, mary3chil
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 07:19 AM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.