Saving CoreData to-many relationships in Swift
In a one-to-many relationship, it is easier to set the "to-one" direction of the
inverse relationships, in your case just
list.board = board
so that the extension methods are actually not needed here.
swift core data how should I save and fetch the one to many relationship and assign value to my viewModel entity
Rather creating relation like this you can do it saving the class id in teacher and student and get them on the basis of id like as:
class ClassEntity {
let id:String
var classTitleName: String
var classRank: Int
init (id:String,
classTitleName: String,
classRank: Int) {
self.id = id
self.classTitleName = classTitleName
self.classRank = classRank
}
}
then your teacher and student
class StudentEntity {
var classId:String
var studentName: String
var studentGender: String
init(classId:String,studentName: String,
studentGender: String){
self.classId = classId
self.studentName = studentName
self.studentGender = studentGender
}
}
class TeacherEntity {
var classId:String
var teacherName: String
var teacherGender: String
init(classId:String,teacherName: String,
teacherGender: String){
self.classId = classId
self.teacherName = teacherName
self.teacherGender = teacherGender
}
}
then create coredatastack
import Foundation
import CoreData
class CoreDataStack: NSObject {
private let modelName: String
lazy var managedContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()
init(modelName: String) {
self.modelName = modelName
}
private lazy var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: self.modelName)
container.loadPersistentStores { (storeDescription, error) in
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
}
}
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
return container
}()
func saveContext () {
guard managedContext.hasChanges else { return }
do {
try managedContext.save()
} catch let error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
}
}
func updateContext() {
do {
try managedContext.save()
} catch let error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
}
}
func clearChanges() {
managedContext.rollback()
}
func deleteReminder(reminder:Reminder) {
managedContext.delete(reminder)
updateContext()
}
func deleteNote(note:Note) {
managedContext.delete(note)
updateContext()
}
func deleteFromIds(selectedId:SubCategoryIds) {
managedContext.delete(selectedId)
updateContext()
}
}
then create a manager
import Foundation
import CoreData
class CoreDataManager {
static let shared = CoreDataManager()
private init(){}
lazy var coreDataStack = CoreDataStack(modelName: "YourModelName")
func allClasses() -> [ClassEntity] {
let fetechRequest: NSFetchRequest<ClassEntity> = ClassEntity.fetchRequest()
do {
let results = try coreDataStack.managedContext.fetch(fetechRequest)
return results
} catch {
}
return [ClassEntity]()
}
func allStudentOfClass(classId:String) -> [StudentEntity] {
let fetechRequest: NSFetchRequest< StudentEntity > = StudentEntity.fetchRequest()
fetechRequest.predicate = NSPredicate(format: "classId == %@",
argumentArray: [classId])
do {
let results = try coreDataStack.managedContext.fetch(fetechRequest)
return results
} catch {
}
return [StudentEntity]()
}
func allTeacherOfClass(classId:String) -> [TeacherEntity] {
let fetechRequest: NSFetchRequest<TeacherEntity> = TeacherEntity.fetchRequest()
fetechRequest.predicate = NSPredicate(format: "classId == %@",
argumentArray: [classId])
do {
let results = try coreDataStack.managedContext.fetch(fetechRequest)
return results
} catch {
}
return [TeacherEntity]()
}
}
how you can create a class
func createClass() {
let id = "Class 1" //or whatever you want to say here
let _class = Class(context: CoreDataManger.shared.coreDataStack.managedContext)
_class.id = id
_class.classTitleName = "Title"
_class.classRank = 12
CoreDataManger.shared.coreDataStack.saveContext()
}
same as how create teacher with this class
func addTeacher(classId:String) {
let _class = TeacherEntity(context: CoreDataManger.shared.coreDataStack.managedContext)
_class.classId = classId
_class.teacherGender = "Male"
_class.teacherName = "Alex"
CoreDataManger.shared.coreDataStack.saveContext()
}
Swift CoreData, saving data via a many to many relationship
You need to create the parent or assign an existing object as the parent, it doesn't just exist automatically.
CoreData • How to modify a many-to-many-Relationship in CoreData using Swift 5?
When you create relationships in your model then Xcode will generate methods for getting and setting data through does relationships. For a to-many relationship you will get a getter <relationship name>
and two setters addTo<relationship name>
So in this case you can update the relationships using addToBooks
and addToPersons
Many To Many with additional data using Swift and Core Data
Core Data hides the correlation table if you use Many-2-Many (without any additional attributes). This means, in the inverse way, that you need to create a correlation table yourself. You can do this, if you create a new Entity in Core Data, which should have a 2-One relationship to both other Entities.
Without extra attributes:
Entity1 <-> Entity2 (The correlation table is hidden, but is there)
With extra attributes:
Entity1 <- CorrelationEntity(with extra attributes) -> Entity2
Core Data One to Many Relationship not saving correctly/as expected
You are creating a new, single instance of newFaction
outside of your for faction in arrayOfFactions
loop. So that single newFaction
is used each time the loop runs and just assigns new values to it (overwriting previous values) resulting in it ending up with the last set of values. Hence you seeing a single faction with the 'last' set of values. Move the line:Let newFaction = Factions(context: contectTCCEDJ)
Inside (at the beginning) of the for in
loop.
Edit: you are adding your faction to a Set (which by definition requires unique entities) so all you're currently doing is re-adding the same faction each time rather than a new one. To-many relationships point to a Set.
Saving data into a One-to-many CoreData relationship in Swift
Comment
has a to-one relationship to Listing
. Just set this relationship.
newComment.listing = listing
Related Topics
How to Set Image in Circle in Swift
How to Disable Calayer Implicit Animations
How to Keep an Iphone/iPad Web App in Full Screen Mode
How to Add Buttons to Navigation Controller Visible After Segueing
Objc_Sync_Enter/Objc_Sync_Exit Not Working with Dispatch_Queue_Priority_Low
How to Check If a Uialertcontroller Is Already Presenting
Opengl Es 2.0 Object Picking on iOS
iOS 9.3:An Ssl Error Has Occurred and a Secure Connection to the Server Cannot Be Made
iOS Provisioning and Certifcates - Will Revoke/Renew Effect App Store Apps
Remembering Scroll Position on Uitableview
Loading a Resource (E.G. Storyboard) in a Swift Framework
Run a Swift 2.0 App Forever in Background to Update Location to Server
Adding Click Event on Infowindow/Marker in Google Maps Sdk for Native iOS/Objective C
How to Get the Build Uuid in Runtime and the Image Base Address
Uiview Animation Jumps at Beginning