您好我正在努力弄清楚如何遍历下面的数组并将每一行添加到我的核心数据实体
非常感谢任何帮助
//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];
我不知道该怎么做。
for () {
NSLog(@"importing Row");
}
以下是我将导入的属性的日志,在命令
中提供 NSLog(@"%@",importArray);
因为csv包含列名
(
CONTACTNAME,
PHONE,
COMPANYNAME,
NOTES
),
答案 0 :(得分:4)
如果您拥有的只有4个物体,请不要打扰循环,只需 -
如果你有一个客户子类,你可以使用:
newCustomer.contactName = [importArray objectAtIndex:0];//change it to the correct index, and correct property name
newCustomer.phone = [importArray objectAtIndex:1];
//....And so on
否则你需要使用
[newCustomer objectForKey:@"contactName"] = [importArray objectAtIndex:0];
<强> BUT 强>
如果您的CSV中有许多属性,则可以在实体中设置其他数组键 -
for(NSUInteger i=0;i<[importArray count];i++){
[newCustomer objectForKey:[keysArry objectAtIndex:i]] = [importArray objectAtIndex:i];
}
有时更好
如果你有很多属性,那么更好的办法就是使用 -
//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];
}
修改强> 要对您的实体进行子类化:
<强>顺便说一句强>