I need to save NSStrings from an array into a .csv file in my documents directory, which is not a problem, but I don’t know how to handle the carriage return.. I specify that I want to apply a carriage return every 8 cells and this happens correctly. However when it comes to write the actual CSV file an extra unwanted comma is added after the carriage return! This is the incriminated line:
NSString *ArrayConvertedIntoStringFINAL = [FinalStringsArrayWithCarriageReturns componentsJoinedByString:@","];
How can I tell the compiler not to apply a comma after a carriage return?
Here is the complete code. Thanks guys!
//Add a Carriage Return symbol every N objects (every FREQUENCY)
int FREQUENCY = 8;
//Define String WithCarriageReturns
NSMutableArray *FinalStringsArrayWithCarriageReturns = [[NSMutableArray alloc] initWithCapacity:0];
for (int i = 1; i <= [FinalStringsArray count]; i++)
{
NSString *readValue = [FinalStringsArray objectAtIndex:i-1];
//Add objects to the final string
[FinalStringsArrayWithCarriageReturns addObject:readValue];
if ( (i % FREQUENCY) == 0) //Number is multiple of N
{
//Every multiple of N add the Carriage Return symbol
[FinalStringsArrayWithCarriageReturns addObject:CarriageReturn];
}
}
NSLog(@"+2+Broken down array strings: %@",FinalStringsArrayWithCarriageReturns);
//PROBLEM! A comma is added after the Carriage Return
//Convert Array into String
NSString *ArrayConvertedIntoStringFINAL = [FinalStringsArrayWithCarriageReturns componentsJoinedByString:@","];
The approach you have posted results in 2 additional copies of every string. That’s a lot of wasted memory. Here’s a simpler approach that only requires a single extra copy and no extra arrays:
Depending on how much data you need to write, it would be even better to write directly to a file instead of the mutable string. This would result in no extra copy of the data and would be faster than writing to the mutable string first.