【发布时间】:2012-09-10 20:21:31
【问题描述】:
此代码引发“CoreData:错误:(19) PRIMARY KEY 必须是唯一的”错误。
Day 实体只有一个when 属性,即NSDate,以及一个称为tasks 的一对多关系。为什么会出现这个错误?如果已经存储了具有特定日期的Day,则获取它,否则我将其插入。因此,对于每个 day 对象,应该有一个不同的 when 属性。我不确定这是否是主键。如何解决这个问题?先感谢您。
NSMutableSet *occurrences = nil;
occurrences = ...
NSMutableOrderedSet *newSet = [NSMutableOrderedSet orderedSetWithCapacity:[occurrences count]];
for(NSDate *current in occurrences) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// try to find a corresponding Day entity whose when attribute is equal to the current occurrence
// if none is available, create it
Day * day = [[self getDayForDate:current inManagedObjectContext:moc] retain];
if(!day){
day = (Day *) [NSEntityDescription insertNewObjectForEntityForName:@"Day" inManagedObjectContext:moc];
}
day.when = current;
[day addTasksObject:aTask];
[newSet addObject:day];
[moc insertObject:day];
[moc processPendingChanges];
[day release];
[pool release];
}
- (Day *)getDayForDate:(NSDate *)aDate inManagedObjectContext:(NSManagedObjectContext *)moc
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Day" inManagedObjectContext:moc];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(when == %@)", aDate];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
[request release];
Day *theDay = nil;
if(array && [array count] == 1){
theDay = [array objectAtIndex:0];
}
return theDay;
}
【问题讨论】:
-
我猜你不需要插入新的一天,如果你已经有了它(这是
day不为零的情况)。特别是我指的是[moc insertObject:day];。你为什么这样做? -
如果您使用
insertNewObjectForEntityForName,该方法会在您保存 moc 时为您插入对象。如果您需要修改它(您已检索到非零日),请修改并保存。此外,我会在循环结束时执行processPendingChanges(仅出于性能原因)。 -
@Flex_Addicted,你是对的。现在 Day 对象被无条件插入。这大概就是问题的根源。我会验证这一点。但是,我无法在循环结束时保存,因为其他对象都在周围并且仍然需要编辑。我会让你知道的。
-
第一条评论中的勘误表:为什么要使用它? 然后,如果无法保存,请将
processPendingChanges移动到 for 循环的末尾。祝你有美好的一天。 -
好的,它现在按预期工作。吸取的教训:永远不要在深夜工作,现在看来这似乎微不足道(但不是今天晚上)。如果您将您的 cmets 改写为答案,我将很高兴接受它。再次感谢您。