xcode 如何在目标 C 中生成二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10527521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to produce 2 dimensional Array in Objective C
提问by Joe Shamuraq
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.
当我尝试添加更多二维数组时,它会不断覆盖第一行。
回答by MByD
Create NSMutableArrayand assign NSMutableArrays to it as its objects.
创建NSMutableArray并分配NSMutableArrays 作为它的对象。
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];
回答by rooster117
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.
它变得非常冗长,但这是我知道如何做到这一点的方式。根据您的需要,一系列字典可能更适合您的情况。
回答by tGilani
I wrote an NSMutableArraywrapper for easy use as a Two Dimensional array. It is available on github as CRL2DArrayhere . https://github.com/tGilani/CRL2DArray
我写了一个NSMutableArray包装器以便于用作二维数组。它在 github 上可用,如CRL2DArray这里 。https://github.com/tGilani/CRL2DArray
回答by Prasad tj
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];
}

