2011-07-15 56 views
0

我讀取一個CSV文件,現在我解析字符串並將元素寫入2D NSMutableArray。NSMutableArray寫入問題?

因爲我正在向2D數組寫入元素,NSLog輸出預期的元素。

但是,當我完成解析並將整個文件寫入二維數組時,NSLog顯示該行每列的每行最後一個元素。

- 如果行中的每個元素都被替換。 ???爲什麼,先進的謝謝你...

for (int i = 1; i < iM; i++) {//was a 1 to pass over the header 
    //get the row and break up into columns 
    nsmarrDummy = [NSMutableArray arrayWithArray:[[nsmarrRow objectAtIndex: i] componentsSeparatedByString: nsstrColParse]]; 


    //write each item to the proper column in the 2d array at the given row 
    for (int j = 0; j < iN; j++) {//<<-- 
     [[nsmarrData objectAtIndex:j] replaceObjectAtIndex:i-1 withObject: [nsmarrDummy objectAtIndex:j]]; 
     NSLog(@"i:%d j:%d item:%@", i, j, [[nsmarrData objectAtIndex:j] objectAtIndex:i-1]); 
    } 

} 
//all the following are the same value, but doing the NSLog as it was writing was correct. 
NSLog(@"FINAL: i:%d j:%d item:%@", 0, 4, [[nsmarrData objectAtIndex:4] objectAtIndex:0]); 
NSLog(@"FINAL: i:%d j:%d item:%@", 0, 5, [[nsmarrData objectAtIndex:5] objectAtIndex:0]); 
NSLog(@"FINAL: i:%d j:%d item:%@", 0, 6, [[nsmarrData objectAtIndex:6] objectAtIndex:0]); 

回答

1

這是我看到在你的例子中,除了潛伏在那裏的問題一些嚴重的鞭打。可可可以爲你做這麼多工作。它有雷電吸引力。讓它在你身邊:

// Get the contents of the file. 
// Real apps never ignore their errors or potential nil results. 
// For this example, assume path exists. 

NSString *fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL]; 

NSMutableArray *nsmarrData = [NSMutableArray array]; 

NSArray *lines = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; 
for (NSString *line in lines) 
{ 
    // Guard against the last line being only a return. 

    if ([line length] > 0) 
    { 
     NSArray *tokens = [line componentsSeparatedByString:@","]; // assuming no space as well 
     [nsmarrData addObject:tokens]; 
    } 
} 

這產生一個NSMutableArray填充每行NSArrays。每行需要一個NSMutableArray?沒問題。相反的:

[nsmarrData addObject:tokens]; 

你可以使用:

[nsmarrData addObject:[NSMutableArray arrayWithArray:tokens]]; 

當然,這一切都不佔不同的上線項目的數量;你需要稍後提防。

祝你好運。