在核心数据 iOS 中设置自动增量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24406501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:05:20  来源:igfitidea点击:

Set auto increment in Core data iOS

ioscore-dataxcode5auto-incrementnsmanagedobject

提问by Anu Padhye

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?

我正在使用 Core Data,并希望将 auto_increment ID 设置为唯一的字段之一。是否可以使用核心数据在 iOS 中设置 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.

下面是我在数据库中插入记录的代码。在第一个字段“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"];

回答by Tom Harrington

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.

Core Data 没有自动增量功能。它在内部使用 SQLite 的事实几乎是无关紧要的——如果你专注于类似 SQL 的细节,你会得到 Core Data 的严重错误。

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.

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

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

但是您可能不需要这个字段。Core Data 已经为每个托管对象处理了唯一的 ID——参见NSManagedObjectID

回答by nahlamortada

Here is something you can do but after saving the Entry So make sure calling saveContext() before you get that else you gonna always get zero

这是你可以做的事情,但是在保存条目之后所以确保在你得到之前调用 saveContext() 否则你总是会得到零

objective-C

目标-C

- (int)getAutoIncrement:(InAppMessage*)inApp {
    int number = 0;
    NSURL *url = [[inApp objectID] URIRepresentation];
    NSString *urlString = url.absoluteString
    NSString *pN = [[urlString componentsSeparatedByString:@"/"] lastObject];
    if ([pN containsString:"p"]){
        NSString *stringPart = [pN stringByReplacingOccurrencesOfString:@"p" withString:@""]
        number = stringPart.intValue
    }
    url = nil;
    urlString = nil;
    pN = nil;
    stringPart = nil;
    return number;
}

Swift:

迅速:

func getAutoIncremenet() -> Int64   {
    let url = self.objectID.uriRepresentation()
    let urlString = url.absoluteString
    if let pN = urlString.components(separatedBy: "/").last {
        let numberPart = pN.replacingOccurrences(of: "p", with: "")
        if let number = Int64(numberPart) {
            return number
        }
    }
    return 0
}