有那麼一瞬間,懶得用NSArray,NSNumber,NSValue等一大堆蛋疼的轉換,因此就定義了一個C的二維數組,反正OC支持C混編,但是蛋疼每每是傳遞的,這裏不疼了,哪裏就要疼,想把一個c的二維數組當成參數傳遞給另外一個函數怎麼辦?各類嘗試,最後想了一個辦法,給你們分享下,不必定是最好的,你們有好的歡迎交流,廢話很少說,上代碼。數組
int dataArray[10][8] ={ {0, 0, 10, 0, 0, 0, 22, 0}, {0, 5, 10, 30, 0, 30, 21, 0}, {5, 20, 50, 40, 10, 50, 19, 0}, {5, 40, 60, 50, 20, 60, 17, 0}, {12, 60, 80, 60, 40, 80, 14, 0}, {20, 80, 80, 80, 80, 80, 12, 0}, {10, 60, 60, 60, 60, 60, 11, 0}, {10, 40, 40, 40, 30, 40, 10, 0}, {5, 20, 20, 20, 0, 20, 9, 0}, {0, 10, 10, 10, 0, 10, 8, 0} }; //不是不容許傳麼,nsdata總能夠吧,反正本質都是二進制,轉過去唄
NSData *data = [NSData dataWithBytes:dataArray length:sizeof(int) * 8 * 10]; //下面提供了兩種轉換回來的方式,爲何提供兩種,本身體會吧,第二種記得使用完了Free()掉,否則………… int dataArray2[10][8]; [data getBytes:dataArray2 length:sizeof(int) * 8 * 10]; int * dataArray3 = malloc(sizeof(int) * 8 * 10); [data getBytes:dataArray3 length:sizeof(int) * 8 * 10]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 10; j++) { NSLog(@"%d", *(dataArray3 + 8 * i + j)); } }
free(dataArray3);
16年9月8日更新:函數
其實簡單的是直接傳遞指針,數組的本質是一個連續的地址+一個指針,因此你能夠這樣spa
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. int dataArray[10][8] ={ {0, 0, 10, 0, 0, 0, 22, 0}, {0, 5, 10, 30, 0, 30, 21, 0}, {5, 20, 50, 40, 10, 50, 19, 0}, {5, 40, 60, 50, 20, 60, 17, 0}, {12, 60, 80, 60, 40, 80, 14, 0}, {20, 80, 80, 80, 80, 80, 12, 0}, {10, 60, 60, 60, 60, 60, 11, 0}, {10, 40, 40, 40, 30, 40, 10, 0}, {5, 20, 20, 20, 0, 20, 9, 0}, {0, 10, 10, 10, 0, 10, 8, 0} }; [self test:dataArray]; } - (void)test:(int *)data { for (int i = 0; i < 8; i++) { for (int j = 0; j < 10; j++) { NSLog(@"%d", *(data + 8 * i + j)); } } }