Kristen Martinson
Kristen Martinson

Reputation: 1869

NSMutableArray writing issue?

I read in a CSV file and now I am parsing the string and writing the element to a 2D NSMutableArray.

AS I am writing the elements to the 2D array the NSLog outputs the expected element.

But when I am done parsing and writing the whole file to the 2D array, the NSLog shows the last element at each row for each column at that row.

--as if every element in the row was replaced. ??? why, thank you in advanced...

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]);

Upvotes: 0

Views: 275

Answers (1)

Extra Savoir-Faire
Extra Savoir-Faire

Reputation: 6036

That is some serious thrash I'm seeing in your example, aside from the problem lurking there. Cocoa can do so much of the work for you. It's got thunder appeal. Let it be on your side:

// 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];
    }
}

This produces a NSMutableArray filled with NSArrays for each row. Need a NSMutableArray for each row? No problem. Instead of:

[nsmarrData addObject:tokens];

you can use:

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

Of course, none of this accounts for varying numbers of items on a line; you'll need to beware of that later.

Good luck to you in your endeavors.

Upvotes: 1

Related Questions