在實際的項目開發中,二維數組也是常常用到的資料結構。OC中的二維數組也是通過一維數組來建立的,今天我們來詳解一下如何在OC中使用二維數組。
【使用NSArray初始化二維數組】
使用NSArray初始化的一維數組和二維數組都是不可變數組。
#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) { @autoreleasepool { //定義2個一維數組; NSArray *firstRow = [[NSArray alloc] initWithObjects:@"1",@"2",@"3", nil]; NSArray *secondRow = [[NSArray alloc] initWithObjects:@"4",@"5",@"6", nil]; //使用一維數組來初始化二維數組; NSArray *my2DArray = [[NSArray alloc] initWithObjects:firstRow,secondRow, nil]; //輸出二維數組對象; NSLog(@"二維數組:%@",my2DArray); //遍曆二維數組; for (int i = 0; i < [my2DArray count]; i++) { for (int j = 0; j < firstRow.count; j++) { NSLog(@"二維數組元素:%@",[[my2DArray objectAtIndex:i] objectAtIndex :j]); } } } return 0;}
列印結果如下:
。
【使用NSMutableArray初始化二維數組】
使用NSMutableArray初始化的一維數組和二維數組都是可變的,可以進行修改和插入操作;
#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) { @autoreleasepool { NSMutableArray *firstRow = [[NSMutableArray alloc] initWithObjects:@"11",@"22",@"33", nil]; NSMutableArray *secondRow = [[NSMutableArray alloc] initWithObjects:@"44",@"55",@"66", nil]; NSMutableArray *my2DArray = [[NSMutableArray alloc] initWithObjects:firstRow,secondRow, nil]; //插入一個資料 [[my2DArray objectAtIndex:0] insertObject:@"iOS" atIndex:3]; NSLog(@"%@",my2DArray); [[my2DArray objectAtIndex:1] insertObject:@"OC" atIndex:0]; NSLog(@"%@",my2DArray); } return 0;}
列印結果如下:
。
【使用for-in快速遍曆二維數組】
#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) { @autoreleasepool { //定義2個一維數組; NSArray *firstRow = [[NSArray alloc] initWithObjects:@"1",@"2",@"3", nil]; NSArray *secondRow = [[NSArray alloc] initWithObjects:@"4",@"5",@"6", nil]; //使用一維數組來初始化二維數組; NSArray *my2DArray = [[NSArray alloc] initWithObjects:firstRow,secondRow, nil]; //遍曆二維數組; for (int i = 0; i < [my2DArray count]; i++) { for (int j = 0; j < firstRow.count; j++) { NSLog(@"二維數組元素:%@",[[my2DArray objectAtIndex:i] objectAtIndex :j]); } } //列印某個維度一維數組 NSLog(@"一維數組:%@",[my2DArray objectAtIndex:0]); //使用for-in快速遍曆二維數組中的一維數組 for (NSArray *arr in my2DArray) { NSLog(@"二維數組中的一維數組:%@",arr); } //使用for-in快速遍曆二維數組中的每一個元素 for (NSArray *arr in my2DArray) { for (NSString *str in arr) { NSLog(@"for-in結果:%@",str); } } } return 0;}
列印結果:
。
github首頁:https://github.com/chenyufeng1991 。歡迎大家訪問。