[英]How to produce 2 dimensional Array in Objective C
How do i produce a 2 dimensional NSMutable array as this: 我如何生成二维NSMutable数组,如下所示:
Array: 数组:
=>[item1]=>[item1a,item1b,item1c...]
=>[item2]=>[item2a,item2b,item2c...]
...
=>[item10]=>[item10a,item10b,item10c...]
So far i've only been successful up to the [item1]=>[item1a,item1b,item1c...] 到目前为止,直到[item1] => [item1a,item1b,item1c ...],我才成功
When i try to add more 2 dimensional array it keeps overriding the first row. 当我尝试添加更多的二维数组时,它会不断覆盖第一行。
Create NSMutableArray
and assign NSMutableArray
s to it as its objects. 创建
NSMutableArray
和分配NSMutableArray
s到它作为对象。
For example: 例如:
NSMutableArray * myBig2dArray = [[NSMutableArray alloc] init];
// first internal array
NSMutableArray * internalElement = [[[NSMutableArray alloc] init] autorelease];
[internalElement addObject:@"First - First"];
[internalElement addObject:@"First - Second"];
[myBig2dArray addObject:internalElement];
// second internal array
internalElement = [[[NSMutableArray alloc] init] autorelease];
[internalElement addObject:@"Second - First"];
[internalElement addObject:@"Second - Second"];
[myBig2dArray addObject:internalElement];
To make a 2 dimensional array you would make an array of arrays. 要制作二维数组,您需要制作一个数组数组。
NSArray *2darray = [NSArray arrayWithObjects: [NSArray arrayWithObjects: @"one", @"two", nil], NSArray arrayWithObjects: @"one_2", @"two_2", nil]];
It gets very verbose but that is the way I know how to do this. 它变得非常冗长,但这就是我知道如何执行此操作的方式。 An array of dictionaries may be better for your situation depending on what you need.
根据您的需要,一系列词典可能更适合您的情况。
I wrote an NSMutableArray
wrapper for easy use as a Two Dimensional array. 我编写了一个
NSMutableArray
包装器,以方便地用作二维数组。 It is available on github as CRL2DArray
here . 它可以在github上以
CRL2DArray
。 https://github.com/tGilani/CRL2DArray https://github.com/tGilani/CRL2DArray
First you to have set An NSMutableDictionary on .h file 首先,您需要在.h文件上设置一个NSMutableDictionary
@interface MSRCommonLogic : NSObject
{
NSMutableDictionary *twoDimensionArray;
}
then have to use following functions in .m file
- (void)setValuesToArray :(int)rows cols:(int) col value:(id)value
{
if(!twoDimensionArray)
{
twoDimensionArray =[[NSMutableDictionary alloc]init];
}
NSString *strKey=[NSString stringWithFormat:@"%dVs%d",rows,col];
[twoDimensionArray setObject:value forKey:strKey];
}
- (id)getValueFromArray :(int)rows cols:(int) col
{
NSString *strKey=[NSString stringWithFormat:@"%dVs%d",rows,col];
return [twoDimensionArray valueForKey:strKey];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.