核心数据中的自动增量对象ID?

时间:2011-06-16 18:23:49

标签: iphone core-data xcode4

我正在处理几种具有多种关系的NSManagedObject类型。如何告诉Core Data为我自动填充对象ID?我正在寻找类似于SQL中的索引键的东西,因此不允许给定对象的两个实例具有相同的ID。

修改

我希望我的所有“帐户”对象都有唯一的ID。我只是在`countForFetchRequest中添加了一个,但我意识到当删除倒数第二个对象然后添加一个时,最后两个对象现在具有相同的ID。

如何确保给定值对于我的“帐户”NSManagedObject的所有实例都具有唯一值?

EDIT2:

我需要有一个单独的ID用于排序目的。

4 个答案:

答案 0 :(得分:10)

所有NSManagedObjects自动拥有唯一的NSManagedObjectID。没有自定义自动递增属性的概念,但是自己编写它很容易。

答案 1 :(得分:4)

我解决这个问题的方法是使用Core Data聚合。我实际上最终自己分配了ID。

基本上,我查询Core Data获取我的实体的所有实体ID,然后遍历它们。如果我发现ID高于当前临时ID,我会使临时ID高于聚合ID。当我完成后,我自动拥有一个高于列表中最高ID的ID。我看到的唯一缺陷就是缺少ID。 (我相信这也有一个简单的解决办法。)

//
//  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 ...
//

答案 2 :(得分:3)

加入您的EDIT2和Edit3,以下答案将帮助您..假设您的id字段为NSNumber,其中unsignedInt为ID。

1)获取相应实体的所有记录。

NSError *error = nil;
NSArray *array = [self fetchAllFileEntity:&error];

2)找到属于该结果的最大数量。

NSNumber *maxValue = nil;
if (array)
    maxValue = [array valueForKeyPath:@"@max.uniqueId.unsignedIntegerValue"];
else
    maxValue = [NSNumber numberWithUnsignedInteger:0];

3)将maxValue + 1分配给新实体

entity.uniqueId = [NSNumber numberWithUnsignedInteger:maxValue.unsignedIntegerValue+1];

答案 3 :(得分:1)

我已经针对上述问题提出了这个解决方案,希望它对某些人有所帮助。

AppDelegate *appdelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appdelegate managedObjectContext];

NSError *error = nil;

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *chatHist = [NSEntityDescription
                                     entityForName:@"ChatHistory" inManagedObjectContext:context];
[fetchRequest setEntity:chatHist];

int chatIdNumber = 0;

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if ([fetchedObjects count] > 0) {
    ChatHistory *chatHistObj = [fetchedObjects objectAtIndex:[fetchedObjects count]-1];
    chatIdNumber = [chatHistObj.chatId intValue];
}

chatIdNumber = chatIdNumber+1;
ChatHistory *chat_History  = [NSEntityDescription          insertNewObjectForEntityForName:@"ChatHistory" inManagedObjectContext:context];

chat_History.chatId = [NSString stringWithFormat:@"%d",chatIdNumber];
相关问题