Primary Key Behavior in Core Data iPhone

I am creating an application that parses feeds from xml and saves them using Core Data. At the moment, I mean duplicate entries. Each feed that I process contains a unique identifier, which I get in my model as an int. Now I need to tell Core Data not to save this object if another with the same identifier already exists.

As an example, suppose my model has the following properties:

Story.id (int) - primary key
Story.title (NSString)
Story.date (NSDate)

What is the best way to implement this?

My approach was to save a record (array) of all identifiers available in the database, and before inserting anything, check if it exists. This may affect the size of my application, but I feel that this is not the right approach.

+3
source share
2 answers

I see two ways to do this. It seems to me that the latter (your proposed method) is the best solution.

I changed id to primaryKey, because I don’t think it would be nice to use id as the name of a variable or method in Object-C, since this is a keyword. I could work, I never tried. I also suggested that primaryKey is an NSNumber, as this will be stored in Core Data.

One :

for (id data in someSetOfDataToImport) {
    NSFetchRequest * request = [[NSFetchRequest alloc] init];

    [request setEntity:[NSEntityDescription entityForName:@"Story" inManagedObjectContext:context]];
    [request setPredicate:[NSPredicate predicateWithFormat:@"primaryKey = %d", primaryKey]];
    NSUInteger count = [context countForFetchRequest:request error:nil];
    [request release];

    if (count > 0)
        continue;

    // Insert data in Managed Object Context
}

2 , , :

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Story" inManagedObjectContext:context]];
NSArray * allStories = [context countForFetchRequest:request error:nil];
[request release];

NSMutableArray * allPrimaryKeys = [[allStories valueForKeyPath:@"@distinctUnionOfObjects.primaryKey"] mutableCopy];

for (id data in someSetOfDataToImport) {
    if ([allPrimaryKeys containsObject:data.primaryKey])
        continue;

    [allPrimaryKeys addObject:data.primaryKey];

    // Insert data in Managed Object Context
}

[allPrimaryKeys release];
+8

. .

, iPhone , , . , XML- .

, , , . , , , , .

+3

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


All Articles