2010-10-07 39 views
2

我有一個應用程序,它導入一個.CSV文件並將每行都轉換爲存儲在數據庫中的核心數據對象。我要導入的CSV文件大約有40個列,每個列映射到Core Data對象的一個​​屬性。導入多種格式時維護列數據的最佳方法

當我開始這個項目,當時只有我正在同一個CSV格式,所以我只是寫的未優雅靜態代碼40多歲的線條要導入的文件,如:

... 
newEntity.yearOfConstruction  = [NSNumber numberWithInt:[[currentRow objectAtIndex:35] integerValue]]; 
newEntity.assessedValue   = [NSNumber numberWithInt:[[currentRow objectAtIndex:36] integerValue]]; 
newEntity.squareFootageOfProperty = [NSNumber numberWithInt:[[currentRow objectAtIndex:37] integerValue]]; 
... 

現在我遇到的問題是,我想導入其他CSV文件格式,這些格式的排序方式與我原來的用例不同。

而不是寫switch(CSVFormatType)和添加額外的40行的代碼集,什麼是存儲CSV列到核心數據映射爲任意數CSV文件類型優雅方式,只是一組代碼創建核心數據對象?

謝謝!

回答

0

我正在處理類似的事情。基本上我創建了一個格式數組,其中包含我想要創建的NSDictionary的鍵,這些鍵的索引與csv文件中的列匹配。
這是我到現在爲止:

+ (NSArray *)arrayFromCSV:(NSString *)csv format:(NSArray *)format ignoreHeader:(BOOL)ignore { 
    NSArray *dataRows = [csv componentsSeparatedByString:@"\n"]; 
    NSArray *checkrow = [[dataRows objectAtIndex:0] componentsSeparatedByString:@";"]; 
    NSInteger expectedRowComponents = [checkrow count]; 
    if ([format count] > expectedRowComponents) { 
      // more format keys than components 
      return nil; 
    } 
    NSMutableArray *returnArray = [NSMutableArray array]; 
    for (NSInteger i = 0; i < [dataRows count]; i++) { 
      if (i == 0 && ignore) 
        // ignore first line in csv, "header" 
        continue; 
      NSString *row = [dataRows objectAtIndex:i]; 
      NSArray *rowComponents = [row componentsSeparatedByString:@";"]; 
      if ([rowComponents count] != expectedRowComponents) 
       continue; 
      NSMutableDictionary *tmpDict = [NSMutableDictionary dictionary]; 
      for (NSInteger j = 0; j < [format count]; j++) { 
       if ([format objectAtIndex:j] != [NSNull null]) { 
          [tmpDict setObject:[rowComponents objectAtIndex:j] forKey:[format objectAtIndex:j]]; 
       } 
      } 
      [returnArray addObject:tmpDict]; 
     } 
    NSLog(@"%@", csv); 
    NSLog(@"%@", returnArray); 
    return returnArray; 
} 

但這僅僅是第一步,這僅支持一個非常簡單的FILEFORMAT。具有「;」的單元格里面不支持。

如果CSV格式是這樣的:firstname ; lastname ; zip ; age
和要導入名字,姓氏和年齡您創建這樣

format = [NSArray arrayWithObjects: @"firstname", @"lastname", [NSNull null], @"age", nil]; 

的importformat那麼你會用鑰匙名字得到一個NSDictionary,姓氏,年齡。如果格式更改,則只需使用importformat重新排列數組。

0

你有沒有考慮用適當的字段和位置數組來組建一張表。當出現不同的格式時追加一個新的集合。在生成代碼時使用數據(輸入參數是Set_Id)?

相關問題