HurkNburkS
HurkNburkS

Reputation: 5510

Update CoreData object instead of inserting new object

I am trying to update a current CoreData object however when ever I use my write method its just adding another object to the database, so when I try to read the objects I get dozens of them back depending how long it's been used for.

Here is my code

#pragma mark -- Write
- (void)writeSeriesSearchObj:(NSMutableDictionary *)SearchDic Name:(NSString *)name
{
    // WRITE TO CORE DATA
    NSManagedObjectContext *context = [self managedObjectContext];

    SeriesSearchObj *searchObj = [NSEntityDescription insertNewObjectForEntityForName:@"SeriesSearchObj" inManagedObjectContext:context];


    if ([name isEqualToString:@"Code"]) {
        searchObj.code = [SearchDic objectForKey:@"Code"];
    } else if ([name isEqualToString:@"Name"]) {
        searchObj.name = [SearchDic objectForKey:@"Name"];
    } else if ([name isEqualToString:@"Model"]) {
        searchObj.modelID = [SearchDic objectForKey:@"ModelID"];
    }

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

    // test
    NSMutableArray *temptestA = [self readSearchObj];
    NSLog(@"%@", temptestA);

}

I suspect I am going wrong using insertNewObjectForEntityForName however I am not sure how else to write this method in order for the same object to be updated every time?

Upvotes: 1

Views: 124

Answers (1)

Saqib Saud
Saqib Saud

Reputation: 2795

SeriesSearchObj *searchObj = [NSEntityDescription insertNewObjectForEntityForName:@"SeriesSearchObj" inManagedObjectContext:context];

Will always return you a new object. Use NSFetch to obtain the existing object and then update it.

Upvotes: 1

Related Questions