3

I have three arrays. The first array contains strings, same as the second, however the third one contains NSNumber's. Anyways, back on topic... how can I create a csv (which is an excel/numbers) file like a spreadsheet to contain this data. Is it possible?

These are my three arrays:

locationArray - contains many strings dateArray - contains many strings milesArray - contains many NSNumber's

But each array contains the same amount of objects so (for example in a table view) you can piece the data together in an NSDictionary. It is like a chain.

So then it would look like this:

NSDictionary *firstFlight = [NSDictionary dictionaryWithObjectsAndKeys:[locationArray objectAtIndex: 0], @"FlightName", [dateArray objectAtIndex: 0], @"FlightDate", [milesArray objectAtIndex: 0], @"FlightMiles", nil];

And that dictionary would contain a flight (the functionality of this test app is to log flights). So if I enumerated this using a for loop and replaced objectAtIndex: with the looped number I could get many dictionaries of the flights.

Now that you understand how my data structure works. How can I create an excel/numbers/spreadsheet CSV file to look like this for example (just a screencapture from what it could look like):

(MILES DATA IS JUST MADE UP)

enter image description here

3
  • 1
    What have you tried? to do in creating the output strings? Commented Sep 30, 2012 at 8:29
  • I have not tried anything, since I am very unsure on how to do this Commented Sep 30, 2012 at 10:13
  • well actually, I was planning to create a separate invisible table view and screenshotting it but I like this idea more of creating a CSV file Commented Sep 30, 2012 at 10:16

1 Answer 1

13

NSArray *firstArray, *secondArray, *thirdArray;

NSMutableString *csv = [NSMutableString stringWithString:@"Name,Date,Miles"];

NSUInteger count = [firstArray count];
// provided all arrays are of the same length
for (NSUInteger i=0; i<count; i++ ) {
    [csv appendFormat:@"\n\"%@\",%@,\"%d\"",
        [firstArray objectAtIndex:i],
        [secondArray objectAtIndex:i],
        [[thirdArray objectAtIndex:i] integerValue]
     ];
    // instead of integerValue may be used intValue or other, it depends how array was created
}

NSString *yourFileName = @"your filename";
NSError *error;
BOOL res = [csv writeToFile:yourFileName atomically:YES encoding:NSUTF8StringEncoding error:&error];

if (!res) {
    NSLog(@"Error %@ while writing to file %@", [error localizedDescription], yourFileName );
}

Sign up to request clarification or add additional context in comments.

1 Comment

Works absolutely beautifully... could not ask for something better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.