Creating a two dimensional array in Objective-C

后端 未结 6 522
Happy的楠姐
Happy的楠姐 2020-12-01 09:46

Whats the easiest way to declare a two dimensional array in Objective-C? I am reading an matrix of numbers from a text file from a website and want to take the data and pla

6条回答
  •  天涯浪人
    2020-12-01 09:52

    First you to have set An NSMutableDictionary on .h file

                @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];
                }
    
    
                - (void)printTwoDArray:(int)rows cols:(int) cols
                {
                    NSString *strAllsValuesToprint=@"";
                    strAllsValuesToprint=[strAllsValuesToprint stringByAppendingString:@"\n"];
                    for (int row = 0; row < rows; row++) {
                        for (int col = 0; col < cols; col++) {
    
                            NSString *strV=[self getValueFromArray:row cols:col];
                            strAllsValuesToprint=[strAllsValuesToprint stringByAppendingString:[NSString stringWithFormat:@"%@",strV]];
                            strAllsValuesToprint=[strAllsValuesToprint stringByAppendingString:@"\t"];
                        }
                        strAllsValuesToprint= [strAllsValuesToprint stringByAppendingString:@"\n"];
                    }
    
                    NSLog(@"%@",strAllsValuesToprint);
    
                }
    

提交回复
热议问题