2012-01-05 118 views
2

您好我很努力通过下面的阵列弄清楚如何循环并添加每个一行到我的核心数据实体如何将此数组加载到核心数据实体?

任何帮助,将不胜感激

//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"); 

} 

这里是一个日志我将进口的属性,因为CSV包括列名

(

    CONTACTNAME, 
    PHONE, 
    COMPANYNAME, 
    NOTES 
), 

回答

4

在命令

NSLog(@"%@",importArray); 

提供。如果你已经是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]; 

如果您有许多特性在您的CSV可以设置键的其他阵列在实体和 -

 for(NSUInteger i=0;i<[importArray count];i++){ 
     [newCustomer objectForKey:[keysArry objectAtIndex:i]] = [importArray objectAtIndex:i]; 
    } 

有时会更好

一个更好的方式来处理这个问题,ecpaciely如果你有很多特性是使用 -

//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]; 
} 

编辑 子类的实体:

  1. 在选择实体模型编辑器。
  2. 在Xcode菜单中选择Editor - > Create NSManagedObject Subclass。
  3. 当你想引用它时,import或者@class你的新子类。

BTW

  1. 子类的实体 - 它将使您的生活更轻松,并会导致更好的性能。
  2. 您的实体名称应该是 - 单数的“客户”,因为它只能容纳一个客户。
+0

好吧对不起,我可能简化了我的问题有点太多,只是为了更容易理解。我说我只有四列名称(电话,公司名称,联系人姓名和注释),实际上我有大约30列和400多行。这真的是我想要导入的客户列表,所以我想我会使用您的“for”方法。但是,我收到错误。在第一行中,我得到了'重新定义'和'预期;在'for'语句说明符中。在第二行'接收器类型的NSManagedObject实例消息不会声明一个方法与选择器:'objectForKey:'你能帮我吗? – msec 2012-01-05 07:21:48

+0

好吧,我修正了第一个应该是'for(NSUInteger i = 0; i <[importArray count]; i ++){'我会编辑它,但我没有足够的XP编辑。我如何修复第二行错误并按照你的建议子类化实体? – msec 2012-01-05 07:40:36

+0

编辑我的答案。 – shannoga 2012-01-05 09:40:59