Mos*_*she 6 iphone core-data xcode4
我正在处理几种NSManagedObject有几种关系的类型.如何告诉Core Data为我自动填充对象ID?我正在寻找类似于SQL中的索引键的东西,因此不允许给定对象的两个实例具有相同的ID.
编辑:
我希望我的所有"帐户"对象都有唯一的ID.我只是在`countForFetchRequest中添加一个,但我意识到当删除倒数第二个对象然后添加一个时,最后两个对象现在具有相同的ID.
如何确保给定值对于我的"帐户"NSManagedObject的所有实例都具有唯一值?
EDIT2:
我需要有一个单独的ID用于排序目的.
Bar*_*ark 10
全部NSManagedObjects自动拥有一个独特的NSManagedObjectID.没有自定义自动递增属性的概念,但自己编写一个肯定很容易.
我解决这个问题的方法是使用核心数据聚合。实际上我最终自己分配了 ID。
本质上,我查询核心数据以获取实体的所有实体 ID,然后迭代它们。如果我找到一个比当前临时 ID 高的 ID,我会将临时 ID 设为比聚合 ID 高 1 的值。完成后,我会自动获得一个比列表中最高的 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 ...
//
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16634 次 |
| 最近记录: |