Search code examples
iosswiftcore-datanspredicate

Using objects as CoreData object field type


Is it possible to configure CoreData object field type as an object ?, for example "CustomTimeObject":

import Foundation
import CoreData


extension someObject{

    @nonobjc public class func fetchRequest() -> NSFetchRequest<SomeObject> {
        return NSFetchRequest<SomeObject>(entityName: "SomeObject")
    }

    @NSManaged public var id: UUID
    @NSManaged public var startTime: CustomTimeObject


}

My intention is to use a predicate when calling to Core Data in order to retrive objects with matching "startTime" specific CustomTimeObject field, for example (even though not working):

            var customTime = [CustomTimeObject]
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
              

            let managedContext = appDelegate.persistentContainer.viewContext
              
     
    
            let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "SomeObject")


            fetchRequest.predicate = NSPredicate(format: "startTime.hour > %@ AND startTime.minutes < %@", argumentArray: [8, 11])


              do
              {
                  let results = try managedContext.fetch(fetchRequest)
              
                
                for result in results as! [NSManagedObject] {
                        var timeObject = CustomTimeObject()
                        timeObject.hour=result.value(forKey: "startTime.hour")
                        timeObject.minutes=result.value(forKey: "startTime.minutes")
                        customTime.append(timeObject)
                }
                
              
     
                 
              }
                
              catch
              {
                  print(error)
              }

Solution

  • You should make CustomTimeObject as another entity and make it as a relation inside your first someObject. Look into this link from Apple : Creating Managed Object Relationships