Question

I'm having trouble trying to export saved data from CoreData to a CSV file. My ultimate goal is to save the information to CSV and attach it in an email. Here's my code for exporting the data:

- (IBAction)exportData
{
mieleWasherAppDelegate *exportObjects = [[mieleWasherAppDelegate alloc] init];
[exportObjects managedObjectContext];
NSFetchRequest * allContacts = [[NSFetchRequest alloc] init];
[allContacts setEntity:[NSEntityDescription entityForName:@"Contacts"     inManagedObjectContext: [exportObjects managedObjectContext]]];
//  [allContacts setIncludesPropertyValues:YES]; //only fetch the managedObjectID

NSError * error = nil;
NSArray * entries = [[exportObjects managedObjectContext] executeFetchRequest:allContacts error:&error];
[allContacts release];
//error handling goes here
NSMutableArray *array = [[NSMutableArray alloc] init];

for (Contacts * entry in entries) 
{
    NSLog(@"Salutation: %@", entry.Salutation);
    NSLog(@"First Name: %@", entry.FirstName);
    NSLog(@"Last Name: %@", entry.LastName);
    NSLog(@"Company Name: %@", entry.CompanyName);
    NSLog(@"Email Address: %@", entry.EmailAddress);
    NSLog(@"Phone Number: %@", entry.PhoneNumber);
    [array addObject:entry];
}
NSError *saveError = nil;
[[exportObjects managedObjectContext] save:&saveError];
//more error handling here

// Export to CSV code
NSString *separator = @", ";
NSString *csv = @"";
for (NSArray *entry in entries) 
{
    csv = [NSString stringWithFormat:@"%@%@%@%@%@\n", csv, [entry Salutation],
           separator, [entry FirstName], 
           separator, [entry LastName], 
           separator, [entry CompanyName], 
           separator, [entry EmailAddress], 
           separator, [entry PhoneNumber]];
}
//If you want to store in a file the CVS
//[csv writeToFile:pathToFile atomically:YES];
//If you want to store in a file the CVS
//[cvs writeToFile:pathToFile atomically:YES];
}

Sorry if the formatting is a bit messy, but it's returning the following warning (repeated):

NSArray may not respond to '-Salutation'

etc. until it goes through all fields. I can't seem to figure out why it wont cooperate. Any advice?

Was it helpful?

Solution

In your second for loop in the code you copy & pasted above, you're declaring entry as a NSArray object instead of a Contacts object.

Change NSArray to Contacts and the warning will go away.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top