2012-05-14 73 views
0

我第一次在這裏問問題,對不起,但我找不到類似的問題。 因此,我需要實體「城市」屬性 - @「名稱」中的更新數據。 舉例在我的核心數據中我已經擁有@「紐約」,@「波士頓」。 並通過解析XML我有NSMutableArray *城市=(@「紐約」,@「波士頓」,@「洛杉磯」,@「華盛頓」);核心數據目標C更新實體內容

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *attributeString = @"name"; 
    NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
//save to the TableView 
cell.textLabel.text = [[object valueForKey:attributeString] description]; 
if ((indexPath.row + 1) == numberOfSectionsInTableView && (self.isParsingDone)) 
     [self.insertNewObjectToCities:nil]; 
//When coredata updating - tableView is also updating automatically 


//Here is just adding new data, but I do not know how to update 
- (void)insertNewObjectToCities_translation:(id)sender 
{ 
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; 
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity]; 
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; 
NSString *attributeString = @"name"; 

if (![[self.parseCities.Cities objectAtIndex:i] isEqualToString:[newManagedObject valueForKey:attributeString]]) 
{ 
    [newManagedObject setValue:[self.parseCities.Cities objectAtIndex:i] forKey:attributeString]; 
    NSLog(@"OBBB %@", [self.parseCities.Cities objectAtIndex:i]); 
    NSLog(@"dessss %@", [[newManagedObject valueForKey:attributeString] description]); 

    i++; 

    if (i==[self.parseCities.Cities count]) 
    { 
     i = 0; 
     return; 
    } 
    else 
    { 
     NSLog(@"valueForKey %@", [newManagedObject valueForKey:attributeString]); 
     [self insertNewObjectToCities_translation:nil]; 
    } 
} 
else 
{ 
    NSLog(@"else"); 
    return; 
} 

// Save the context. 
NSError *error = nil; 
if (![context save:&error]) { 
    // Replace this implementation with code to handle the error appropriately. 
    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 

} 

回答

1

要更新管理對象,首先需要把它拿來,請對場中的任何變化,所取得的NSManagedObject,然後保存你用來獲取對象的上下文。如果再次調用insertNewObjectForEntityForName,它將每次插入一個新的託管對象,即使它已經存在於核心數據中。

每次需要檢查並查看是否需要添加新對象時,獲取單個對象的速度非常慢。您可能想要將當前已加載的對象(或其唯一標識字段)緩存到NSArrayNSSet中,以便您可以檢查該成員身份。