核心数据中的自动增量对象ID? [英] Auto-Incremented Object ID in Core Data?
问题描述
我使用几个 NSManagedObject
类型与几个关系。我如何告诉Core Data自动为我填充对象ID?我在SQL中寻找类似索引键的东西,所以给定对象的两个实例不允许有相同的ID。
I am working with several NSManagedObject
types with several relationships. How can I tell Core Data to automatically populate object IDs for me? I'm looking for something like an index key in SQL, so that no two instances of a given object are allowed to have the same ID.
编辑:
我想让我的所有帐户对象拥有唯一的ID。我只是添加一个到countForFetchRequest,但我意识到,当删除第二个到最后一个对象,然后添加一个,最后两个对象现在有相同的ID。
I'd like for all of my "Account" objects to have unique IDs on them. I was just adding one to the `countForFetchRequest, but I realized that when deleting the second to last object and then adding one, the last two objects now have the same IDs.
EDIT2:
我需要一个单独的ID用于排序。
I need to have a separate ID for sorting purposes.
推荐答案
我解决这是与Core Data聚合。我实际上最终自己分配ID。
The way I resolved this is with Core Data aggregates. I actually end up assigning the ID myself.
基本上,我查询Core Data的所有实体ID,然后遍历它们。如果我发现一个ID高于当前临时ID,我使临时ID高一个高于聚合。当我完成后,我自动有一个高于列表中最高的ID。我唯一的缺点,我看到这是如果有一个缺少的ID。 (我相信这也有一个简单的解决方案。)
Essentially, I query Core Data for all of the entity IDs of my entity and then iterate through them. If I find an ID which is higher than the current temporary one, I make the temporary ID higher one higher than the aggregated one. When I'm done, I automatically have an ID which is higher than the highest one in the list. The only flaw I see with this is if there is a missing ID. (I believe that there is a simple fix for this as well.)
//
// Create a new entity description
//
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:self.managedObjectContext];
//
// Set the fetch request
//
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[fetchRequest setEntity:entity];
//
// We need to figure out how many
// existing groups there are so that
// we can set the proper ID.
//
// To do so, we use an aggregated request.
//
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:@"entityID"]];
NSError *error = nil;
NSArray *existingIDs = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error != nil) {
//
// TODO: Handle error.
//
NSLog(@"Error: %@", [error localizedDescription]);
}
NSInteger newID = 0;
for (NSDictionary *dict in existingIDs) {
NSInteger IDToCompare = [[dict valueForKey:@"entityID"] integerValue];
if (IDToCompare >= newID) {
newID = IDToCompare + 1;
}
}
//
// Create the actual entity
//
MyEntity *newEntity = [[MyEntity alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
//
// Set the ID of the new entity
//
[newEntity setEntityID:[NSNumber numberWithInteger:newID]];
//
// ... More Code ...
//
这篇关于核心数据中的自动增量对象ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!