Reputation: 252
Hi I am struggling to figure out how to loop through the array below and add each row into my core data entity
Any help would be greatly appreciated
//CREATE AN ARRAY FROM CSV DOCUMENT USING CHCSVPARSER
NSError *error;
NSString *customerCSV = [[NSBundle mainBundle] pathForResource:@"CUSTOMERS" ofType:@"csv"];
NSArray *importArray = [NSArray arrayWithContentsOfCSVFile:customerCSV encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@",importArray);
//LOOP THROUGH CREATED ARRAY AND ADD OBJECTS TO COREDATA CUSTOMER ENTITY
Invoice_MarketAppDelegate* delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* managedObjectContext = delegate.managedObjectContext;
NSManagedObject* newCustomer;
newCustomer = [NSEntityDescription insertNewObjectForEntityForName:@"Customers" inManagedObjectContext:managedObjectContext];
I don't know what to do here.
for () {
NSLog(@"importing Row");
}
Here is a log of the attributes I will be importing, provided at the command
NSLog(@"%@",importArray);
since the csv included column names
(
CONTACTNAME,
PHONE,
COMPANYNAME,
NOTES
),
Upvotes: 2
Views: 1082
Reputation: 19869
If all you have is 4 objects, don't bother looping you can simply -
If you have a sub class of Customers you can use:
newCustomer.contactName = [importArray objectAtIndex:0];//change it to the correct index, and correct property name
newCustomer.phone = [importArray objectAtIndex:1];
//....And so on
else you will need to use
[newCustomer objectForKey:@"contactName"] = [importArray objectAtIndex:0];
BUT
If you have many properties in your CSV you can set an other array of the keys in your entity and -
for(NSUInteger i=0;i<[importArray count];i++){
[newCustomer objectForKey:[keysArry objectAtIndex:i]] = [importArray objectAtIndex:i];
}
Better sometimes
A better way to handle this, ecpaciely if you have many properties is to use -
//1. crate a dictionary from your CSV with keys that are similar to your entity property names.
NSDictionary *csvDictinary = []//set your dictionary.
//2.get all the property names from your customers entity
NSDictionary *attributes = [[NSEntityDescription
entityForName:@"Costumer"
inManagedObjectContext:self] attributesByName];
//3. set the properties to your entity
for (NSString *attr in attributes) {
[Costumer setValue:[csvDictinary valueForKey:attr] forKey:attr];
}
EDIT To sub class your entity:
BTW
Upvotes: 4