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

前端 未结 9 1560
暖寄归人
暖寄归人 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:12

    Update to @Lukasz answer in Swift:

    static func nextAvailble(_ idKey: String, forEntityName entityName: String, inContext context: NSManagedObjectContext) -> Int {
        let fetchRequest: NSFetchRequest = 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 
    }
    

提交回复
热议问题