3

I am using core data in my Swift-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??

My programatical try where katid is my unique key:

    let fetchRequest = NSFetchRequest(entityName: "Kategorien")
    let sortDescriptor = NSSortDescriptor(key: "katid", ascending: true, selector: #selector(NSString.compare(_:)))
    fetchRequest.sortDescriptors = [sortDescriptor]


    var newID = 0
    do {
        let result = try managedObjectContext.executeFetchRequest(fetchRequest).last as! Kategorien!
        if result != nil {
            newID = (result.katid?.integerValue)! + 1
        }
    } catch let error as NSError {
        NSLog("Unresolved error \(error)")
    }

Any better solution ;-)

Ulli H
  • 1,748
  • 1
  • 19
  • 32
  • 1
    http://stackoverflow.com/questions/33504947/coredata-ios-how-to-create-unique-id-for-objects – Wain May 27 '16 at 14:18
  • @Wain i´m getting "9D87E220-A3D6-4DC1-90AA-EA98810B3765", What´s wrong here? :-( – Ulli H May 27 '16 at 14:36
  • nothing, that's a UUID / GUID - i didn't close your question as it isn't an exact dupe of that other one but it holds pertinent information and potentially a solution you can work with. it's certainly more efficient than your solution, but so is counting and sorting your fetch in reverse order with a fetch batch size... – Wain May 27 '16 at 14:43
  • @Wain ok, but what´s about sorting? I´ve to sort with this value... Or should i add a new "column" like _order_? – Ulli H May 27 '16 at 15:43
  • I see you are sorting, missed that earlier. So just set the fetch batch size to 1 as you only care about the last item, and sort in the other direction because you only want one result (sort descending) – Wain May 27 '16 at 17:41
  • @Wain sure, i need sorting. But to be straight: i can´t understand your answer. :-( Let´s say, i have 3 rows to sort. How can i do this with GUIDs and one row??? – Ulli H May 27 '16 at 18:28
  • GUID is useful for unique identification, it depends on your goal and usage. If you need an int then sorting and fetching only 1 result is effective. – Wain May 27 '16 at 18:31
  • @Wain did u mean **fetchRequest.fetchLimit = 1**? For that i found a working sample http://stackoverflow.com/questions/34724402/write-auto-increment-id – Ulli H May 28 '16 at 15:35

0 Answers0