如何将新对象插入到实体中并设置该对象与另一个实体的现有对象的关系?
How to insert a new Object into an Entity and set the relationship of that object with an existing object of another entity?
我的问题可以应用于任何类型的关系,但在我的例子中,我有一个一对多。
假设我有一个实体人物,它有 3 个对象:
布莱恩
彼得
斯科特
而且每个人可以有很多工作。所以我有一个当前为空的 Job 实体。两个实体的反向关系已经创建并且效果很好。说明一下,我的问题不是插入对象(我知道怎么做),是具体的插入方式。
所以更具体的问题是:
如何将一个或多个作业对象插入作业实体并将它们中的每一个分配给当前存在于 Core Data 中的一个 Person 对象?
如果您使用的是 CoreData,则您的对象已生成 class。在此生成的 class 中,您将看到如下生成的方法:
- (void)addJobsObject:(CDJob*)value;
- (void)removeJobsObject:(CDAdvert*)value;
- (void)addJobs:(NSSet*)values;
使用它们来设置关系。
第一个:
创造一些就业机会:
let job1 = NSEntityDescription.insertNewObjectForEntityForName("Job", inManagedObjectContext: managedObjectContext) as! Job
...
第二个:
检索那些工作:
// Request
let moc = managedObjectContext
let jobFetch = NSFetchRequest(entityName: "Job")
// Filtring
let jobTitle1 = "job1"
jobFetch.predicate = NSPredicate(format: "jobTitle == %@", jobTitle)
do {
let fetchedJobs = try moc.executeFetchRequest(jobFetch) as! [Job] // JOBS
} catch {
fatalError("Failed to fetch jobs: \(error)")
}
第三名:
检索人:
// Request
let moc = managedObjectContext
let personFetch = NSFetchRequest(entityName: "Person")
// Filtring
let firstName = "Person1"
personFetch.predicate = NSPredicate(format: "firstname == %@", firstName)
do {
let fetchedJobs = try moc.executeFetchRequest(personFetch) as! [Person] // PERSONS
} catch {
fatalError("Failed to fetch persons: \(error)")
}
第四名:
将工作分配给人员:
let person1 = (personFetch as! [Person])[0]
let job1 = (fetchedJobs as! [Job])[0]
person1.job = job1
PS:已编码但未测试
在尝试了很多事情之后,我终于找到了解决办法。感谢 Jimmy,他提出了如何解决这个问题的想法。关键是要意识到您不能将多个对象分配给一个已经存在的对象(或者至少我找不到一种方法来做到这一点),但是您可以将许多对象添加到一个现有的对象中。换句话说,您不能将实体分配给集合,反之亦然。
SWIFT 3
所以 第一步 是获取一个对象(在本例中为 Person),您要分配多个对象(在此案例乔布斯)到。这会让你到达那里:
var person = try MOC.fetch(Person.fetchRequest()).filter { [=10=].name == "Brian" }
第二步是创建Jobs的托管对象:
let job = Jobs(context: MOC)
job.title = "Computers"
第三步 是通过您获取的人添加对象:
person[0].addToJobs(job)
如果您想添加多个作业,那么您可以创建一个 for 循环并创建任意数量的托管对象,并在它们准备好保存时添加它们。例如:
for title in jobsTitles {
let job = Jobs(context: MOC)
job.title = title
person[0].addToJobs(job)
}
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func fetchData()
{
do
{
task1 = try context.fetch(Contact.fetchRequest())
}
catch
{
print("Error fetching data from CoreData")
}
}
func filtering()
{
do {
let contactIdentifier : String = searchVariable.text!
let formatRequest : NSFetchRequest<Contact> = Contact.fetchRequest()
formatRequest.predicate = NSPredicate(format: "first_name CONTAINS[c] '\(contactIdentifier)'")
let fetchedResults = try context.fetch(formatRequest)
if let aContact = fetchedResults.first
{
searchResult = fetchedResults
}
contactListngTable.reloadData()
}
catch {
print ("fetch task failed", error)
}
}
@IBAction func saveButton(_ sender: Any)
{
let task = Contact(context:context)
task.first_name = firstNameTextbox.text
task.last_name = lastNameTextbox.text
task.phone_number = phoneNumberTextbox.text
(UIApplication.shared.delegate as! AppDelegate).saveContext()
_ = navigationController?.popViewController(animated: true)
}
@IBAction func loguotButton(_ sender: Any)
{
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "logout") as! ViewController
self.present(newViewController, animated: true, completion: nil)
}
func authinication()
{
let username : String = usernameTextbox.text!
let pasword : String = passwordTextbox.text!
let parameter : Parameters = ["email": "\(username)" , "password": "\(pasword)" ]
Alamofire.request("https://reqres.in/api/login", method:.post, parameters:parameter
).responseJSON { response in
switch response.result {
case .success(let value):
//print(response)
let forToken = JSON(value)
let token = forToken["token"]
let error = forToken["error"]
if(token.type == SwiftyJSON.Type.null)
{
self.errorMessageLabel.text = error[].stringValue
}
else
{
self.performSegue(withIdentifier: "loginSuccess", sender: nil)
}
case .failure(let error):
print(error)
}
}
}
我的问题可以应用于任何类型的关系,但在我的例子中,我有一个一对多。
假设我有一个实体人物,它有 3 个对象:
布莱恩
彼得
斯科特
而且每个人可以有很多工作。所以我有一个当前为空的 Job 实体。两个实体的反向关系已经创建并且效果很好。说明一下,我的问题不是插入对象(我知道怎么做),是具体的插入方式。
所以更具体的问题是:
如何将一个或多个作业对象插入作业实体并将它们中的每一个分配给当前存在于 Core Data 中的一个 Person 对象?
如果您使用的是 CoreData,则您的对象已生成 class。在此生成的 class 中,您将看到如下生成的方法:
- (void)addJobsObject:(CDJob*)value;
- (void)removeJobsObject:(CDAdvert*)value;
- (void)addJobs:(NSSet*)values;
使用它们来设置关系。
第一个:
创造一些就业机会:
let job1 = NSEntityDescription.insertNewObjectForEntityForName("Job", inManagedObjectContext: managedObjectContext) as! Job
...
第二个:
检索那些工作:
// Request
let moc = managedObjectContext
let jobFetch = NSFetchRequest(entityName: "Job")
// Filtring
let jobTitle1 = "job1"
jobFetch.predicate = NSPredicate(format: "jobTitle == %@", jobTitle)
do {
let fetchedJobs = try moc.executeFetchRequest(jobFetch) as! [Job] // JOBS
} catch {
fatalError("Failed to fetch jobs: \(error)")
}
第三名:
检索人:
// Request
let moc = managedObjectContext
let personFetch = NSFetchRequest(entityName: "Person")
// Filtring
let firstName = "Person1"
personFetch.predicate = NSPredicate(format: "firstname == %@", firstName)
do {
let fetchedJobs = try moc.executeFetchRequest(personFetch) as! [Person] // PERSONS
} catch {
fatalError("Failed to fetch persons: \(error)")
}
第四名:
将工作分配给人员:
let person1 = (personFetch as! [Person])[0]
let job1 = (fetchedJobs as! [Job])[0]
person1.job = job1
PS:已编码但未测试
在尝试了很多事情之后,我终于找到了解决办法。感谢 Jimmy,他提出了如何解决这个问题的想法。关键是要意识到您不能将多个对象分配给一个已经存在的对象(或者至少我找不到一种方法来做到这一点),但是您可以将许多对象添加到一个现有的对象中。换句话说,您不能将实体分配给集合,反之亦然。
SWIFT 3
所以 第一步 是获取一个对象(在本例中为 Person),您要分配多个对象(在此案例乔布斯)到。这会让你到达那里:
var person = try MOC.fetch(Person.fetchRequest()).filter { [=10=].name == "Brian" }
第二步是创建Jobs的托管对象:
let job = Jobs(context: MOC)
job.title = "Computers"
第三步 是通过您获取的人添加对象:
person[0].addToJobs(job)
如果您想添加多个作业,那么您可以创建一个 for 循环并创建任意数量的托管对象,并在它们准备好保存时添加它们。例如:
for title in jobsTitles {
let job = Jobs(context: MOC)
job.title = title
person[0].addToJobs(job)
}
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func fetchData()
{
do
{
task1 = try context.fetch(Contact.fetchRequest())
}
catch
{
print("Error fetching data from CoreData")
}
}
func filtering()
{
do {
let contactIdentifier : String = searchVariable.text!
let formatRequest : NSFetchRequest<Contact> = Contact.fetchRequest()
formatRequest.predicate = NSPredicate(format: "first_name CONTAINS[c] '\(contactIdentifier)'")
let fetchedResults = try context.fetch(formatRequest)
if let aContact = fetchedResults.first
{
searchResult = fetchedResults
}
contactListngTable.reloadData()
}
catch {
print ("fetch task failed", error)
}
}
@IBAction func saveButton(_ sender: Any)
{
let task = Contact(context:context)
task.first_name = firstNameTextbox.text
task.last_name = lastNameTextbox.text
task.phone_number = phoneNumberTextbox.text
(UIApplication.shared.delegate as! AppDelegate).saveContext()
_ = navigationController?.popViewController(animated: true)
}
@IBAction func loguotButton(_ sender: Any)
{
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "logout") as! ViewController
self.present(newViewController, animated: true, completion: nil)
}
func authinication()
{
let username : String = usernameTextbox.text!
let pasword : String = passwordTextbox.text!
let parameter : Parameters = ["email": "\(username)" , "password": "\(pasword)" ]
Alamofire.request("https://reqres.in/api/login", method:.post, parameters:parameter
).responseJSON { response in
switch response.result {
case .success(let value):
//print(response)
let forToken = JSON(value)
let token = forToken["token"]
let error = forToken["error"]
if(token.type == SwiftyJSON.Type.null)
{
self.errorMessageLabel.text = error[].stringValue
}
else
{
self.performSegue(withIdentifier: "loginSuccess", sender: nil)
}
case .failure(let error):
print(error)
}
}
}