CoreDataのrelational

MySQLのconcatに近いか。
userFetch.predicate = NSPredicate(format: “name = %@”, “John”) で条件一致を求める。

override func viewDidLoad() {
        super.viewDidLoad()
        
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedContext = appDelegate.persistentContainer.viewContext
        let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)!
        let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
        
        user.setValue("John", forKeyPath: "name")
        user.setValue("john@test.com", forKey: "email")
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy/MM/dd"
        let date = formatter.date(from: "1990/10/08")
        user.setValue(date, forKey: "date_of_birth")
        
        user.setValue(0, forKey: "number_of_children")
        
        let carEntity = NSEntityDescription.entity(forEntityName: "Car", in:managedContext)!
        let car1 = NSManagedObject(entity: carEntity, insertInto: managedContext)
        car1.setValue("Audi TT", forKey: "model")
        car1.setValue(2010, forKey: "year")
        car1.setValue(user, forKey: "user")
        
        let car2 = NSManagedObject(entity: carEntity, insertInto: managedContext)
        car2.setValue("BMW X6", forKey: "model")
        car2.setValue(2014, forKey:"year")
        car2.setValue(user, forKey: "user")
        
        do {
            try managedContext.save()
        } catch {
            print("Failed saving")
        }

        let userFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
        userFetch.fetchLimit = 1
        userFetch.predicate = NSPredicate(format: "name = %@", "John")
        userFetch.sortDescriptors = [NSSortDescriptor.init(key: "email", ascending: true)]
        
        let users = try! managedContext.fetch(userFetch)
        
        let john: User = users.first as! User
        
        print("Email: \(john.email!)")
        let johnCars = john.cars?.allObjects as! [Car]
        print("has \(johnCars.count)")

    }

ちょっと雑だが、次は地図に行ってみよう。