Can we define auto increment attribute in core data?

0 votes
asked Nov 3, 2010 by javal-nanda

Hello I am using core data in my application, and want to set ID attribute in every entity as autoincrement. Is it possible in core data? Or I have to manually insert the entry and manage the increment programatically??

3 Answers

0 votes
answered Nov 3, 2010 by drekka

If you are thinking of the id for the primary keys then core data handles this for you. On each object there is an objectID property you can access to see it. When you create an object from the managed object context, core data assigns a temporary id. When you commit the changes from the managed object context, core data assigns a perminant id. I don't think it would be a good idea to manually try and set this.

Read this stackoverflow thread for more details.

0 votes
answered Sep 15, 2017 by nik-kov

I used that way with NSFetchedResultsController:

first sorting:

fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)]

Then in add object method:

// Minimum id value
var recordID = 1
if let lastRecordID = fetchedResultsController.fetchedObjects?.first?.id {
    recordID = Int(lastRecordID) + 1
}

let newRecord = Record(context: persistentContainer.viewContext)
newRecord.id = Int32(recordID)
0 votes
answered Sep 15, 2017 by nmortada

You can do it like that after

saveContext()

Objective-c:

- (int)getAutoIncrement {
    int number = 0;
    NSURL *url = [[self 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
}
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...