开发者

How to insert distinct records through core data in iPhone?

I want to insert only those records in core data in iPhone which are not already present in the sqllite table. In other words, I want to insert distinct records in my core data table. My code of insertion is

for(NSInteger j=0;j<[items count];j++){
            Story *story=(Story *)[NSEntityDescription insertNewObjectForEntityForName:@"Story" inManagedObjectContext:managedObjectContext];

            [story setTitle:[[items objectAtIndex:j] objectForKey:@"titl开发者_开发问答e"]];
            [story setDate:[[items objectAtIndex:j] objectForKey:@"date"]];
     }

Tell me the way to insert only distinct records in this.


Have a look at this page, the section 'Implementing Find-or-Create Efficiently' gives detailed info on how to implement an update/insert mechanism.


One solution might be to give your entity an index attribute (just an integer value), and check for this before you add a new entity.

Alternatively, if you don't want duplicates to be possible, you could simply perform a fetch on stories with the same title and date. If none are returned from this fetch, then add the new object as in your own code. You can implement it like this:

NSString *title = [[items objectAtIndex:i] objectForKey:@"title"];
NSDate *date = [[items objectAtIndex:i] objectForKey:@"date"];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Story" inManagedObjectContext:managedObjectContext];

// Create the predicates to check for that title & date.
NSString *predTitleString = [NSString stringWithFormat:@"%@ == %%@", @"title"];
NSString *predDateString = [NSString stringWithFormat:@"%@ == %%@", @"date"];

NSPredicate *predTitle = [NSPredicate predicateWithFormat:predTitleString, @"title"];
NSPredicate *predDate = [NSPredicate predicateWithFormat:predDateString, @date];

NSArray *predArray = [NSArray arrayWithObjects:predTitle, predDate, nil];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predArray];

// Create the fetch request.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];

// Fetch results.
NSError *error = nil;
NSArray *array = [context executeFetchRequest:fetchRequest error:&error];

// If no objects returned, a story with this title & date does not yet exist in the model, so add it.
if ([array count] == 0) {
    Story *story=(Story *)[NSEntityDescription insertNewObjectForEntityForName:@"Story" inManagedObjectContext:managedObjectContext];

    [story setTitle:title];
    [story setDate:date];
}

[fetchRequest release];

I have found it very useful to implement a utility class that contains generic methods to perform these fetches, so all you have to do is tell it the name of your entity, a dictionary of keys & values to check for, and the context to search in. Saves rewriting a lot of code!

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜