views:

931

answers:

3

I am trying to figure out how to do either nested arrays or multidimensional array for iPhone SDK programming using objective-c.

My data would be something like this, 3 columns and rows from 10 to 50.

name     department     year
John     Sales          2008
Lisa     Sales          2009
Gina     Support        2007

Any help is appreciated

+1  A: 

Hello,

Could you perhaps make a structure like this:

struct UserInfo
{
 string name;
 string department;
 int year;
}

struct UserInfo users[3];
users[0].name = "John";

etc....

and make an array out of the structure so you wouldn't have to deal with multidimensional arrays? If not then just ignore me! :)

CalebHC
I agree, this is a much cleaner solution than using arrays of arrays.
amischiefr
In order to do this in Objective-C, you'd need to make it an object rather than a struct (as structs cannot do proper memory management of their contents).
Chuck
+1  A: 

Nesting arrays is the only really practical way to do a multidimensional array in Cocoa. You could define a category on NSArray with methods like objectAtRow:column: to make accessing items more convenient. Though in your case, I agree with Caleb that it doesn't look like you need this — your data looks like an array of objects.

Chuck
+3  A: 

I'm not sure whether it's your example or your terminology, but that's not really a multi-dimensional array, that's an array of records. I'd make each of your records a class:

@interface Employee
  NSString* name;
  NSString* dept;
  NSString* year;
@end

@property (nonatomic,retain) NSString* name;
@property (nonatomic,retain) NSString* dept;
@property (nonatomic,retain) NSString* year;

// ... rest of class def


Employee* a = [[Employee alloc] init];
a.name = @"Bob";
a.dept = @"Sales";
a.year = @"2008";

// declare others

NSArray* array = [NSArray arrayWithObjects:a,b,c,nil];
[a release];

This is more Objective C-ish than using a struct.

If you really do mean a multi-dimensional array then there's nothing wrong with the "obvious" approach. Of course you might want to wrap it up in a class so you can also write some utility methods to make it easier to deal with.

Stephen Darlington
Yeah, my code is pretty old school!
CalebHC
Thank you all for your help. I tried using this approach, but how would you retrieve the values back?Employee* a = [[Employee alloc] init];a.name = @"Bob";a.dept = @"Sales";a.year = @"2008";Employee* b = [[Employee alloc] init];b.name = @"Gina";b.dept = @"Support";b.year = @"2007";NSString *yourData = [array objectAtIndex:indexPath.row];The above line yourData causes an error. How should I retrieve values for example the Year value for row two?
Podcaster123
What's in your .m file? Did you add a @synthesize line for each property?
Stephen Darlington
Yes I do have @synthesize in my .m file and I have the above code in the same .m file. The .h file has the @property.
Podcaster123