For example two models Person and Car. Person has many cars. My question is how to add car to already created Person. If I tray in AddNewCarView:
var person: Person
...
var newCar = Car(context: viewContext)
newCar.name = name
newCar.model = model
And now, what...?
newCar.person = person (gives newCar to all persons)
Or.
person.addToCars(newCar)
Is that something I have to add in predicate? In Car I have:
static func fetchCars() -> NSFetchRequest<Car> {
let request: NSFetchRequest<Car> = Car.fetchRequest()
reqest.predicate = NSPredicate(format: "", ) ..?
request.sortDescriptors = [NSSortDescriptor(keyPath: \Car.timestamp, ascending: true)]
return request
}
Related
I am trying to compose a dynamic filter in my Codre Data filters like this (using SwiftUI):
#State var NumberOfRooms: Int
init(NumberOfRooms: Int) {
self.NumberOfRooms = NumberOfRooms
}
#FetchRequest(entity: Listing.entity(),sortDescriptors:[NSSortDescriptor(keyPath: \Listing.publishdate, ascending: false),],predicate: NSPredicate(format: "category == %# AND rooms ", "House", "\($NumberOfRooms)"))
In the view i want to modify the value of the variable like this:
Text("2")
.onTapGesture {
self.NumberOfRooms = 2
}
I get the error at NSPredicate:
Cannot use instance member '$NumberOfRooms' within property initializer; property initializers run before 'self' is available
Basically i want to dynamically compose the predicates.
Any help is deeply appreciated.
Initialize your request inside the init like this.
var fetchRequest: FetchRequest<Listing>
#State var NumberOfRooms: Int = 10
init(NumberOfRooms: Int) {
fetchRequest = FetchRequest<BlogIdea>(entity: Listing.entity(),sortDescriptors:[],predicate: NSPredicate(format: "category == %# AND rooms ", "House", "\(NumberOfRooms)"))
self.NumberOfRooms = NumberOfRooms
}
I have reached an impasse. I would like to display data from CoreData to be edited and then update it back into the database. There doesn't seem to be any way to do this but it is such a basic operation I'm sure the problem is on my end.
Here's the code I have
import SwiftUI
import CoreData
struct CustomerEditView: View
{
#Environment(\.managedObjectContext) var context
#State var firstName = ""
#State var lastName = ""
#State var phone = ""
#State var email = ""
#State var birthday = ""
var customer: Customer
var body: some View
{
//firstName = customer.firstName!
//lastName = customer.lastName!
//phone = customer.phone!
//email = customer.email!
return VStack
{
TextField("First Name", text: $firstName)
TextField("Last Name", text: $lastName)
TextField("Cell Phone", text: $phone)
TextField("EMail", text: $email)
TextField("Birthday", text: $birthday)
Button("Save")
{
do
{
//customer.birthday = self.birthday
customer.firstName = firstName
customer.lastName = lastName
customer.phone = phone
customer.email = email
try context.save()
}
catch
{
print(error.localizedDescription)
}
}
}
}
}
I've tried a number of ways to update the State variables from the CoreData Customer entity but there doesn't seem to be any way in SwiftUI to do this without triggering warnings about modifying the state values during an update operation. I'll accept any solution but it seems like there should be a means of accomplishing this without needing to use temporary state variables, just references to the core data attributes.
Here is a way to go
struct CustomerEditView: View
{
#Environment(\.managedObjectContext) var context
#State var firstName: String // << declare only
// ... other states are the same
var customer: Customer
init(customer: Customer) {
self.customer = customer
// create state with initial value from customer
_firstName = State(initialValue: customer.firstName ?? "") // << here !!
// ... other states are the same
}
var body: some View
{
// .. other your code
I have EmployeeExample and Deptt as entities.
EmployeeExample one to one relationship with Dept
Dept has more than one relationship with EmployeeExample
I want to save data through relationship. I have dept entity object, with that I want to save employeeexample entity
I achieved this, but I want to know whether it is the optimal way. Any optimal way? I would like to know how the relationship works.
My code :
import UIKit
import CoreData
class ViewController: UIViewController {
var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var empSet = NSSet()
var empS = Set<EmployeeExample>()
override func viewDidLoad() {
super.viewDidLoad()
var context:NSManagedObjectContext = (container?.viewContext)!
let dept = NSEntityDescription.insertNewObject(forEntityName: "Deptt", into: context) as! Deptt
let emp = NSEntityDescription.insertNewObject(forEntityName: "EmployeeExample", into: (container?.viewContext)!) as! EmployeeExample
emp.firstName = "YYYY"
emp.lastName = "HHHHHHH"
empS.insert(emp)
print("Count of Emp SSSS Set == \(empS.count)")
let emp1 = NSEntityDescription.insertNewObject(forEntityName: "EmployeeExample", into: (container?.viewContext)!) as! EmployeeExample
emp1.firstName = "RRRRR"
emp1.lastName = "YYYYY"
empS.insert(emp1)
empSet.addingObjects(from: empS)
dept.deptName = "CCC"
print("Count of Emp SSSS Set == \(empS.count)")
print("Count of Emp Set == \(empSet.count)")
dept.addToEmp(empSet)
do {
try appDelegate.saveContext()
print("Saved -------------")
}catch {}
}
}
Do I have to create an Employee instance each time?
Do I have to create an Employee instance each time?
Well, do you have a new employee each time? If you have new information, you need to create a new Employee record. If you're using existing information, you look up an existing Employee from your persistent store by using NSFetchRequest. You create new instances when you have new data to save. Whether you need to do that is something only you can answer. If you have new data, yes. Otherwise, no.
Please let me know how to save objects through relationship.
If I have two entities like Notes , Category entity
Note is one to one for Category.
Category Many to one for Notes.
How to save , if we have Category context to Notes..
Please provide me some inputs.
How to save through sets. It would be greatful
I have Employee and Department entities. Department has one to many relationship with Employee. Employee has one to one relationship with Department. I want save object of employee entity using department entity.
Each time I have create new Object for Employee –
import UIKit
import CoreData
class ViewController: UIViewController {
var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var empSet = NSSet()
var empS = Set<EmployeeExample>()
override func viewDidLoad() {
super.viewDidLoad()
var context:NSManagedObjectContext = (container?.viewContext)!
let dept = NSEntityDescription.insertNewObject(forEntityName: "Department", into: context) as! Department
let emp = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: (container?.viewContext)!) as! Employee
emp.firstName = "YYYY"
emp.lastName = "HHHHHHH"
empS.insert(emp)
print("Count of Emp SSSS Set == \(empS.count)")
let emp1 = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: (container?.viewContext)!) as! Employee
emp1.firstName = "RRRRR"
emp1.lastName = "YYYYY"
empS.insert(emp1)
empSet.addingObjects(from: empS)
dept.deptName = "CCC"
print("Count of Emp SSSS Set == \(empS.count)")
print("Count of Emp Set == \(empSet.count)")
dept.addToEmp(empSet)
do {
try appDelegate.saveContext()
print("Saved -------------")
}catch {
print("Error")
}
}
}
I have doubt in these lines anEmployee.department = newDepartment How to get the newDepartment value. Whether i have to declare let newDepartment = NSEntityDescription.insertNewObject(forEntityName: "Department", into: (container?.viewContext)!) as! Department.
The Department object here is whatever object should be related to that specific Employee object. How you get it depends on how your app works, but you probably want to do one of these:
If the employee belongs to a new department that doesn't already exist in your app, you create a new instance of Department and assign that object as anEmployee.department.
If the employee belongs to a department that already exists in your app, you use an already existing Department. You probably get that by fetching Department objects from Core Data-- either with NSFetchRequest or by using an NSFetchedResultsController.
I'm a little bit confused try to fetch relation data from coredata in swift
Person Entity
contains the name of person and Unique Id. The relation with Books is ONE to Many
For example
Person Entity:
idPerson = 25 - namePerson = John
idPerson = 26 - namePerson = Steve
Books Entity contains the title of books, Unique Id for the book and a relation ID with person (personBook). The relation with Person is ONE to ONE
For example
Books Entity:
idBook = 2543 - titleBook = title one - personBook = 25
idBook = 2544 - titleBook = title two - personBook = 25
idBook = 2545 - titleBook = title three - personBook = 26
here my data model screenshot: (no image because i have no reputation)
Person class
#objc(Person)
class Person: NSManagedObject {
#NSManaged var idPerson: String
#NSManaged var namePerson: String
#NSManaged var booksRel: NSSet
}
Books class
#objc(Books)
class Books: NSManagedObject {
#NSManaged var bookTitle: String
#NSManaged var idBook: String
#NSManaged var personBook: String
#NSManaged var personRel: Person
}
Fetch code
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let request = NSFetchRequest(entityName: "Books")
request.returnsObjectsAsFaults = false
request.fetchLimit = 30
////////////////////////////
// CODE TO JOIN Person entity WHERE personBook = idPerson
////////////////////////////
var results:NSArray = context.executeFetchRequest(request, error: nil)!
for temp in results {
var data = temp as Books
///////////////////////////////////////
//println(data.namePerson) ----> not working
///////////////////////////////////////
}
is possibile to fetch for every book the related namePerson based on namePerson = personBook ?
Thank you very much!
You don't need a property personBook for your Books entity.
Let's create a Person managedObject (using Swift 1.0):
let person = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: context) as Person
person.idPerson = 23
person.namePerson = "John"
var error: NSError?
if !context.save(&error) {
println("Unresolved error \(error), \(error!.userInfo)")
abort()
}
When you create a Books managedObject, you can link it to person like this:
let book = NSEntityDescription.insertNewObjectForEntityForName("Books", inManagedObjectContext: context) as Books
book.bookTitle = "My book Title"
book.idBook = 2547
book.personRel = person
var error: NSError?
if !context.save(&error) {
println("Unresolved error \(error), \(error!.userInfo)")
abort()
}
Now, when you want to make a fetch on Books, you can do like this:
let fetchRequest = NSFetchRequest(entityName: "Books")
var error: NSError?
var booksArray = context.executeFetchRequest(fetchRequest, error:&error)
if let error = error {
println("Unresolved error \(error), \(error.userInfo)")
abort()
}
for book in booksArray as [Books] {
let person = book.personRel as Person
println(person.namePerson)
println(person.idPerson)
}
If I have understood your question / data structure correctly, you will want to do something like:
let fetchRequest = NSFetchRequest(entityName: "Books")
let bookPersonPredicate = NSPredicate(format: "personRel.idPerson == %#", person.idPerson)
fetchRequest.predicate = bookPersonPredicate