I am having a bit of trouble figuring out this Core Data stuff. How do I create a new entry with a unique ID? In SQL I would just declare one field as an autoincrement fie
That ain't how CoreData works.
In CoreData, you create instances of entities. Each instance is unique. You then retrieve and manipulate instances as needed. CoreData takes care of the persistence for you, including uniquely identifying instances.
Step away from everything you know about traditional relational databases.
CoreData is an awesomely powerful bit of technology that offers features well beyond just database like persistence. It'll save you many lines of code and perform extremely well if you embrace it.
What if we want to sync with a remote database that does need autoincremented id's for unique rows of data? Is there a way to implement autoincremented id's if we need to. I understand it's not required for core data but I need to import data from a remote database and then upload again and make sure the id's are intact.
Update to @Lukasz answer in Swift:
static func nextAvailble(_ idKey: String, forEntityName entityName: String, inContext context: NSManagedObjectContext) -> Int {
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: entityName)
fetchRequest.propertiesToFetch = [idKey]
fetchRequest.sortDescriptors = [NSSortDescriptor(key: idKey, ascending: true)]
do {
let results = try context.fetch(fetchRequest)
let lastObject = (results as! [NSManagedObject]).last
guard lastObject != nil else {
return 1
}
return lastObject?.value(forKey: idKey) as! Int + 1
} catch let error as NSError {
//handle error
}
return 1
}