1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
HurkNburkS
  • 5,492
  • 19
  • 100
  • 183
  • have you read [THIS](http://stackoverflow.com/questions/22247059/core-data-find-or-create-most-efficient-way/22334087#22334087) or [THAT](http://stackoverflow.com/questions/20020442/querying-core-data-for-specific-attributes-when-creating-new-objects-and-returni/20020912#20020912) – Dan Shelly Jun 09 '14 at 04:33

1 Answers1

1
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.

Saqib Saud
  • 2,799
  • 2
  • 27
  • 41
  • What happens if I use fetch the first time but there is no object yet? – HurkNburkS Jun 09 '14 at 21:36
  • 1
    i just created an if statment, if NSFetch dosnt bring anything back (first time normally) then i insertNewObjectForEntityForName etc.. then after that I always use fetch. – HurkNburkS Jun 10 '14 at 02:23