Advertise Books Events Forum News Social Networking Support Us

sdkIQ for iPhone
($4.99)

Shape Up
($0.99)

Your First iPhone App
($1.99)

iVidCam Free
(free)

Kid Art
($0.99)

iPUBQUIZ
(£1.19)

ArtStudio
($3.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum

View Single Post
Old 05-07-2009, 03: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 08:11 PM.
jacobhb is offline   Reply With Quote
 
Enter the iPhone App Challenge!  Win $500!
» Advertisements
» Stats
Members: 24,276
Threads: 39,067
Posts: 171,316
Top Poster: smasher (2,575)
Welcome to our newest member, jstewuk
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 11:41 PM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.