Set auto increment in Core data iOS

狂风中的少年 提交于 2019-12-05 12:44:17

问题


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?

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

回答1:


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.

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.

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




回答2:


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

objective-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
}


来源:https://stackoverflow.com/questions/24406501/set-auto-increment-in-core-data-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!