CoreData, NSManagedObject retrieves or creates if does not exist

I am trying to parse many text files and organize their contents as managed objects. There are many duplicates in text files, so one of the โ€œsideโ€ tasks is to get rid of them.

What I am trying to do in this regard is to check if an entity exists with the given content, and if it is not, I create it. However, I have different objects with different attributes and relationships. What I want is a kind of function that will take several attributes as input and return a new instance of NSManagedObject, and I would not have to worry if it was inserted into or retrieved from the data store.

Is there one?

I must also say that I am noob in the master data.


More details if you want:

I am trying to write a kind of dictionary. I have words (Word {NSString * word, โ†” Rule of rule}), rules (Rule {NSString name, โ†”> Word word, โ†” PartOfSpeech partOfSpeech, <> Endings}), parts of speech (PartOfSpeech {NSString name, โ†” rule rules)) (I hope the notation is clear).

Two words are equal if they have the same word property and are โ€œconnectedโ€ to the same rule. Two rules are the same if they have the same endings and part of speech.

, NSPredicate, NSManagedObjectContext NSEntityDescription , , , , , ( ), NSDictionary , , , , .

. , - , . , , .

+3
2

, . Core Data - . . "upsert". , , , .

+3

. , . , ( ). . , fetch-or-create NSManagedObject .

@implementation MyDataManagerClass

...

@synthesize MyRootDataMO;

- (MyDataManagerClass *) init {

    // Init managed object

   NSManagedObjectContext *managedObjectContext = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

   // Fetch or Create root user data managed object

   NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"MyRootDataMO" inManagedObjectContext:managedObjectContext];
   NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];

   [request setEntity:entityDescription];

   NSError *error = nil;
   NSArray *result = [managedObjectContext executeFetchRequest:request error:&error];

   if (result == nil) {
       NSLog(@"fetch result = nil");
        // Handle the error here
   } else {
       if([result count] > 0) {
           NSLog(@"fetch saved MO");
           MyRootDataMO = (MyRootDataMO *)[result objectAtIndex:0];
       } else {
           NSLog(@"create new MO");
           MyRootDataMO = (MyRootDataMO *)[NSEntityDescription insertNewObjectForEntityForName:@"MyRootDataMO" inManagedObjectContext:managedObjectContext];
       }

   }

   return self;

}

...
+1

Source: https://habr.com/ru/post/1794198/


All Articles