Creating a unique id for a Core Data program on the iPhone

前端 未结 9 1541
暖寄归人
暖寄归人 2020-12-04 07:28

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

相关标签:
9条回答
  • 2020-12-04 08:05

    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.

    0 讨论(0)
  • 2020-12-04 08:08

    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.

    0 讨论(0)
  • 2020-12-04 08:12

    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 
    }
    
    0 讨论(0)
提交回复
热议问题