Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving, deleting and fetching data from a one to many relationship core data

I have created a data model like so:

I have this code for a fetch request:

func roundFetchRequest() -> NSFetchRequest {
    let fetchRequest = NSFetchRequest(entityName: "Customer")
    print("Check here: \(myRoundIndexPath)")
    //let predicate : NSPredicate = NSPredicate(format: "custRoundRel = %@", frc2.objectAtIndexPath(myRoundIndexPath!) as! RoundName) //ASSUME THIS IS CORRECT
    let sortDescriptor = NSSortDescriptor(key: "c2fna", ascending: true)
    //fetchRequest.predicate = predicate
    fetchRequest.sortDescriptors = [sortDescriptor]
    return fetchRequest
}

My commented out code does not give an error, but I cannot seem to save a customer to the RoundName instance. When I save a customer with its attributes, I have used this code:

func newCust() {
    let cont = self.context
    let newCustomer = NSEntityDescription.entityForName("Customer", inManagedObjectContext: cont)
    let aCust = Customer(entity: newCustomer!, insertIntoManagedObjectContext: cont)

    aCust.c2fna = firstName.text
    aCust.c3lna = lastName.text
    aCust.c4tel = tel.text
    aCust.c5mob = mob.text
    aCust.c6ema = email.text
    aCust.c7hsn = houseNo.text
    aCust.c8fir = street.text
    aCust.c9sec = secondLine.text
    aCust.c10ar = area.text
    aCust.c11pc = postcode.text
    aCust.c12cos = cost.text
    aCust.c13fq = frequencyNumber.text
    aCust.c14fqt = frequencyType.text
    let DF = NSDateFormatter()
    aCust.c15das = DF.dateFromString(startDate.text!)
    //Do Pics in a minute & next date in a minute
    aCust.c17notes = notes.text

    //print("Desc = \(picRound.image?.description)")

    do {
        try context.save()
        print("Save Successful")
    } catch {
        print("Save Unsuccessful")
    }
}

What is the code to link this customer with the correct Round?

Thanks, I am very new to core data and really would appreciate any help.

like image 477
agf119105 Avatar asked Jan 25 '16 11:01

agf119105


1 Answers

Yes, you use a predicate on your fetch request, with a format like

NSPredicate(format:"custRoundRel = %@", xxxx) 

where xxxx is the Round instance.

You can also just use the roundCustRel relationship depending on what you want to do with the Customer instances and how many there are.

like image 87
Wain Avatar answered Sep 29 '22 15:09

Wain