Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mitulmanish/befe9b39371cf87794e1c54594fc2edf to your computer and use it in GitHub Desktop.
Save mitulmanish/befe9b39371cf87794e1c54594fc2edf to your computer and use it in GitHub Desktop.
Saving for inverse relationship in Core Data
class CoreDataInverseRelationSaveExample {
@IBAction func saveNewSkill(sender: UIBarButtonItem) {
print("finding User")
let fetchRequest = NSFetchRequest(entityName: "Person")
fetchRequest.predicate = NSPredicate(format: "%K == %@", "userID", CURRENT_USER)
//3
var fetchedUsers = [Person]()
do {
let results =
try managedObjectContext!.executeFetchRequest(fetchRequest)
fetchedUsers = (results as?[
Person])!
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
let associatedUser = fetchedUsers.first
print("User found")
let skillEntity = NSEntityDescription.insertNewObjectForEntityForName("Skill", inManagedObjectContext: managedObjectContext!) as! Skill
skillEntity.setValue(skillName.text, forKey: "skillName")
let hourlyRateInput = hourlyRate.text
if let number = Int(hourlyRateInput!) {
let myNumber = NSNumber(integer: number)
skillEntity.setValue(myNumber, forKey: "hourlyRate")
} else {
print("'\(hourlyRateInput)' did not convert to an Int")
}
let experienceInput = experience.text
if let number = Int(experienceInput!) {
let myNumber = NSNumber(integer: number)
skillEntity.setValue(myNumber, forKey: "experience")
} else {
print("'\(experienceInput)' did not convert to an Int")
}
skillEntity.owner = associatedUser
print("Saving Skill")
do{
try managedObjectContext!.save()
}
catch{
fatalError("Unable to save object")
}
print("Done Saving Skill")
performSegueWithIdentifier("saveSkill", sender: sender)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment