我使用的是Core Data,并且想要将auto_increment ID设置为唯一的字段之一.是否可以在iOS中使用核心数据设置auto_increment?有谁可以帮助我一个小例子如何实现这个?
以下是我在数据库中插入记录的代码.在第一个字段“id”中,我想将其设置为auto_increment,而不是手动插入.
- (NSManagedobjectContext *)managedobjectContext { NSManagedobjectContext *context = nil; id delegate = [[UIApplication sharedApplication] delegate]; if ([delegate performSelector:@selector(managedobjectContext)]) { context = [delegate managedobjectContext]; } return context; } NSManagedobjectContext *context = [self managedobjectContext]; // Create a new managed object NSManagedobject *newObj = [NSEntityDescription insertNewObjectForEntityForName:@"Users" inManagedobjectContext:context]; [newObj setValue:[NSNumber numberWithInt:userId] forKey:@"id"]; [newObj setValue:theFileName forKey:@"Name"];
解决方法
核心数据没有自动增量功能.事实上,它在内部使用sqlite大多是无关紧要的 – 如果您专注于类似sql的详细信息,则会导致Core Data错误.
如果你想增加一个字段,你必须自己管理它.您可以将当前值保存在应用程序的NSUserDefaults中.或者您可以将其放在Core Data使用的持久存储文件的元数据中(请参阅NSPersistentStoreCoordinator上的方法).无论是好的,只要确保查找,增加它,并在创建一个新的对象时重新保存它.
但你可能不需要这个领域.核心数据已经处理每个受管对象的唯一ID – 请参阅NSManagedobjectID.