在Core数据iOS中设置自动增量 [英] Set auto increment in Core data iOS

查看:182
本文介绍了在Core数据iOS中设置自动增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Core Data,并且想要将auto_increment ID设置为唯一的字段之一。是否可以在iOS中使用核心数据设置auto_increment?任何人都可以帮助我一个小例子如何实现这个?

I am using Core Data, and want to set an auto_increment ID as one of the fields which will be unique. Is it possible to set auto_increment in iOS using core data? Can anyone help me with a small example of how to implement this?

下面是在数据库中插入记录的代码。在第一个字段id中,我想将其设置为auto_increment,而不是手动插入它。

Below is the code through which I am inserting records in database. In the first field "id", i want to set it as auto_increment and not manually insert it.

- (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"];


推荐答案

Core Data没有自动递增功能。它在内部使用SQLite的事实大多是不相关的 - 如果你关注类似SQL的细节,你会得到Core Data错误。

Core Data does not have an auto-increment feature. The fact that it uses SQLite internally is mostly irrelevant-- if you focus on SQL-like details, you'll get Core Data badly wrong.

如果你想增加字段,你必须自己管理它。您可以将当前值保存到应用程序的 NSUserDefaults 中。或者可以将其放在Core Data使用的持久存储文件的元数据中(请参阅 NSPersistentStoreCoordinator 上的方法)。或者是很好,只是确保查找它,增加它,并重新保存它,当你创建一个新的对象。

If you want an incrementing field, you'll have to manage it yourself. You can save the current value in your app's NSUserDefaults. Or you could put it in the metadata for the persistent store file that Core Data uses (see methods on NSPersistentStoreCoordinator). Either is fine, just make sure to look it up, increment it, and re-save it when you create a new object.

但你可能不需要这个领域。 Core Data已处理每个受管对象的唯一ID - 请参阅 NSManagedObjectID

But you probably don't need this field. Core Data already handles unique IDs for each managed object-- see NSManagedObjectID.

这篇关于在Core数据iOS中设置自动增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆