2013-07-04 56 views
0

我有一個NSArray其中包含多個NSDictionary。 我在做什麼是打破NSDictionary並將其添加到CoreData,但結果是每個變量(id, alarmDistance, isAlert等)將自己添加到一個單獨的行。 我想要做的是插入一堆od對象NSDictionary保持在同一行。插入multuple NSDictionary到CoreData問題

我的代碼:

- (void)updateTrapsTable 
{ 
    NSArray *node = @[@"alarmDistance", @"id", @"isActive", @"lat", @"lon", @"poly0", @"poly1", @"poly2", @"polygonAzimut1", @"polygonAzimut2", @"polygonAzimut3", @"polys", @"roadNumber", @"trapDescription", @"type", @"degrees", @"direction"]; 

    NSArray *arrayOfTraps = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayOfAllTraps"]; 

    for (int i=0; i < arrayOfTraps.count; i++) // Enumerate all traps 
    { 
     NSMutableDictionary *singleTrap = [[NSMutableDictionary alloc] init]; 
     singleTrap = arrayOfTraps[i]; 

     for (int c=0; c < node.count; c++) // Enumerate all traps' attributes 
     { 
      [self addToCoreData_value:singleTrap[node[c]] key:node[c]]; 
     } 

     NSLog(@"TRAP #%d ADDED TO CORE DATA!", i); 
    } 
} 

- (void)addToCoreData_value:(NSString*)value key:(NSString*)key 
{ 
    NSLog(@"Trying to add record to Core Data"); 

    self.entity = [NSEntityDescription entityForName:@"Trap" inManagedObjectContext:self.managedObjectContext]; 
    self.managedObject = [[NSManagedObject alloc] initWithEntity:self.entity insertIntoManagedObjectContext:self.managedObjectContext]; 

    if ([key isEqualToString:@"id"]) 
    { 
     [self.managedObject setValue:@([value integerValue]) forKey:@"trapID"]; 
    } 
    else if ([key isEqualToString:@"alarmDistance"] || 
     [key isEqualToString:@"degrees"] || 
     [key isEqualToString:@"polys"] || 
     [key isEqualToString:@"roadNumber"] || 
     [key isEqualToString:@"type"]) 
    { 

     [self.managedObject setValue:@([value integerValue]) forKey:key]; 
    } 
    else if ([key isEqualToString:@"lat"] || 
      [key isEqualToString:@"lon"]) 
    { 
     [self.managedObject setValue:@([value floatValue]) forKey:key]; 
    } 
    else if ([key isEqualToString:@"isActive"]) 
    { 
     BOOL toSet = false; 

     if ([value isEqualToString:@"True"]) 
     { 
      toSet = YES; 
     } 
     else 
     { 
      toSet = NO; 
     } 

     [self.managedObject setValue:@(toSet) forKey:key]; 
    } 
    else 
    { 
     [self.managedObject setValue:value forKey:key]; 
    } 


    NSError *error; 
    [self.managedObjectContext save:&error]; 

    NSLog(@"Record added to Core Data"); 
} 

回答

2

addToCoreData_value:方法創建一個新的 「陷阱」 的對象,被稱爲爲每個屬性。

您必須先更改邏輯以創建「陷阱」對象,然後將所有屬性添加到此對象。

+0

我試着添加'[self.managedObjectContext save:&error];' 'NSLog(@「TRAP#%d添加到核心數據!」,i);'將所有屬性設置爲單個對象,但結果相同。 –

+1

@IdanMoshe:'[[NSManagedObject alloc] initWithEntity:...]'創建一個新的對象,而不是保存操作。 –

+0

噢,好的,現在可以使用,非常感謝! –