user137822
user137822

Reputation:

How to create nested array or multidimensional array

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

Upvotes: 1

Views: 6872

Answers (4)

Nafiz
Nafiz

Reputation: 462

from @Stephen example... You can do this to get first employee name.

Employee *e = (Employee *) [array objectAtIndex:0];

NSLog(@"Name: %@", e.name);

Upvotes: 0

Stephen Darlington
Stephen Darlington

Reputation: 52575

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.

Upvotes: 5

Chuck
Chuck

Reputation: 237110

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.

Upvotes: 1

CalebHC
CalebHC

Reputation: 5042

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! :)

Upvotes: 1

Related Questions