how to define 2x2 array in ios?
how to define 2x2 or 3X.. array in ios? like this
[name=john , age=21 , num=1]
[name=max , age=25 , num=2]
[name=petter , age=22 , num=3]
with columns in NSMutableArray you can only add rows with objects; i w开发者_如何学Cant this array[][]
Looking at your example, I wouldn't do it with arrays, or not just arrays. I'd have an array of dictionaries or an array of custom objects with the properties name, age and num. With dictionaries:
NSArray* theArray = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"john", @"name",
[NSNumber numberWithInt: 21], @"age",
[NSNumber numberWithInt: 1], @"num",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"max", @"name",
[NSNumber numberWithInt: 25], @"age",
[NSNumber numberWithInt: 2], @"num",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"petter", @"name",
[NSNumber numberWithInt: 22], @"age",
[NSNumber numberWithInt: 3], @"num",
nil],
nil];
How to declare a two dimensional array of string type in Objective-C? might give you an idea
So many ways ...
NSMutableArray *array = [[NSMutableArray alloc] init];
NSMutableDictionary *person = [[[NSMutableDictionary alloc] init] autorelease];
[person setObject:@"john" forKey:@"name"];
[person setObject:[NSNumber numberWithInt:21] forKey:@"age"];
...
[array addObject:person];
... or create your custom class, which does hold all person data, or struct, or ... Depends on your goal.
It looks like you should be create a proper data storage class to store this in, rather than a dictionary or something like that.
e.g.
@interface Person : NSObject {
}
@property (nonatomic, copy) NSString* Name;
@property int age;
@property int num;
@end
Then create your person instances and store them in an array. You may wich to create some connivence methods first. e.g.
[[NSArray arrayWithObjects:[Person personWithName:@"Bob",Age:1 Num:3],
[Person personWithName:@"Bob",Age:1 Num:3],
[Person personWithName:@"Bob",Age:1 Num:3],nil];
Its much clearer.
精彩评论