3

我只想在 iPhone 的核心数据中插入那些尚未出现在 sqllite 表中的记录。换句话说,我想在我的核心数据表中插入不同的记录。我的插入代码是

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

            [story setTitle:[[items objectAtIndex:j] objectForKey:@"title"]];
            [story setDate:[[items objectAtIndex:j] objectForKey:@"date"]];
     }

告诉我在其中只插入不同记录的方法。

4

2 回答 2

5

看看这个页面,“高效实现查找或创建”部分提供了有关如何实现更新/插入机制的详细信息。

于 2011-09-15T09:43:35.370 回答
3

一种解决方案可能是为您的实体提供一个index属性(只是一个整数值),并在添加新实体之前检查这一点。

或者,如果您不希望重复,您可以简单地对具有相同titleand的故事执行提取date。如果此提取没有返回任何内容,则像在您自己的代码中一样添加新对象。你可以像这样实现它:

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];

我发现实现一个包含通用方法来执行这些获取的实用程序类非常有用,所以您所要做的就是告诉它您的实体名称、要检查的键和值的字典以及要搜索的上下文in. 省去重写大量代码!

希望这可以帮助。

于 2011-09-15T09:57:37.360 回答