gpt4 book ai didi

swift - 将实体数组保存在另一个实体下 CoreDataRelationships

转载 作者:行者123 更新时间:2023-11-30 10:49:34 25 4
gpt4 key购买 nike

我正在开发一款应用程序,商家可以在该应用程序中将一堆产品添加到人员选项卡中。

从表格 View 中选择客户后,用户可以看到产品列表以及我想在该客户名下保存的总金额,以便他稍后付款。我对 CoreData 中的关系做了很多研究,但还没有找到一种方法来一次保存多个项目。

这是 View Controller 的屏幕截图,显示了客户以及要添加到其选项卡中的产品。

Add to tab view controller

我已经创建了数据模型,一切都运行良好,只是无法将产品链接到每个客户。我希望能够单击客户并查看其选项卡中的所有产品。我花了几周的时间试图找到答案,但结果变得非常令人沮丧。只需能够保存和检索项目,我的应用程序就完成了。

真的很期待答案!

import UIKit
import MapKit
import GoogleSignIn
import CoreData

class addToTabViewController: UIViewController {

// Data Arrays
var myCart = [Cart]()
var myCartUz: [Cart] = []

var selectedIndex: Int!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

var amount: String = ""
var transaction: String = ""

@IBOutlet weak var profilePicture: UIImageView!
@IBOutlet weak var customerName: UILabel!
@IBOutlet weak var phoneNumber: UILabel!
@IBOutlet weak var emailAddress: UILabel!
@IBOutlet weak var customerAddress: UILabel!
@IBOutlet weak var profileView: UIView!
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var receiptView: UIView!

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var customerProfile: UIImageView!
@IBOutlet weak var customerProfileView: UIView!
@IBOutlet weak var totalAmount: UILabel!
@IBOutlet weak var merchantName: UILabel!
@IBOutlet weak var merchatEmail: UILabel!

// Variable
var customers: Cutomers!

override func viewDidLoad() {
super.viewDidLoad()

// Show data
configureEntryData(entry: customers)
fetchCartData()
totalAmount.text = amount

// Design parameters
hutzilopochtli()

}

// Info profile button
@IBAction func infoButton(_ sender: Any) {
profileView.isHidden = !profileView.isHidden
receiptView.isHidden = !receiptView.isHidden
customerProfileView.isHidden = !customerProfileView.isHidden
}

// Add to tab button
@IBAction func addToTabButton(_ sender: Any) {


}

// Show customer details
func configureEntryData(entry: Cutomers) {

let name = entry.name
let address = entry.address
let phone = entry.phoneNumber
let email = entry.email

customerName!.text = name
customerAddress!.text = address
phoneNumber!.text = phone
emailAddress!.text = email
self.title = name

let image = entry.profileicture as Data?
profilePicture!.image = UIImage(data: image!)
customerProfile!.image = UIImage(data: image!)

}

// Get cart data
func fetchCartData() {

do {
myCart = try context.fetch(Cart.fetchRequest())
myCartUz = myCart
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {

}

merchantName?.text = GIDSignIn.sharedInstance().currentUser.profile.name
merchatEmail?.text = GIDSignIn.sharedInstance().currentUser.profile.email

}

// Design parameters function
func hutzilopochtli(){

profilePicture.roundMyCircle()
customerProfile.roundMyCircle()
profileView.layer.cornerRadius = 15
receiptView.layer.cornerRadius = 15
profileView.isHidden = true
map.layer.cornerRadius = 13
}
}

// Table view dataSource and delegates

extension addToTabViewController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return myCartUz.count
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "discountCell", for: indexPath) as! discountTableViewCell

let price = myCartUz[indexPath.row].price
let xNSNumber = price as NSNumber

cell.productName?.text = myCartUz[indexPath.row].product
cell.amountLabel?.text = "IDR \(xNSNumber.stringValue)"

return cell
}
}

这是客户类别

class constantCustomer: NSObject {
private class func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext

}

class func saveObject(customerId: String, name: String, phone: String, address: String, email: String, picture: NSData) -> Bool {
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "Cutomers", in: context)
let managedObject = NSManagedObject(entity: entity!, insertInto: context)

managedObject.setValue(customerId, forKey: "customerID")
managedObject.setValue(NSDate(), forKey: "date")
managedObject.setValue(name, forKey: "name")
managedObject.setValue(phone, forKey: "phoneNumber")
managedObject.setValue(address, forKey: "address")
managedObject.setValue(email, forKey: "email")
managedObject.setValue(picture, forKey: "profileicture")
do {
try context.save()
return true
} catch {
return false
}
}


class func fetchObject() -> [Cutomers]? {
let context = getContext()
var myCustomers: [Cutomers]? = nil

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Cutomers")
let sort = NSSortDescriptor(key: "date", ascending: true)
fetchRequest.sortDescriptors = [sort]

do {
myCustomers = try context.fetch(Cutomers.fetchRequest())
return myCustomers
} catch {
return myCustomers
}
}

}

最佳答案

在不了解 Customers 类的情况下,我只能创建一个示例。这是用于保存过程:

func saveCustomer(entry: Customers) {
let entity = NSEntityDescription.entity(forEntityName: "EntityName", in: viewContext)
let customer = Customers(entity: entity!, insertInto: viewContext)

// add data to your customer class
customer.price = price


for journalEntry in entry.entry {
/// Your class with the Relationship
let persistent = CustomersDetail(context: viewContext)
persistent.question = journalEntry.question
persistent.answer = journalEntry.answer
customer.addToRelationship(persistent)
}
/// do saving
do {
try viewContext.save()
} catch let error {
print(error.localizedDescription)
}
}

正在加载特定 CostumerName 的客户:

func loadCustomerData(customerName: String) -> Customers {
let fetch:NSFetchRequest<Customers> = Customers.fetchRequest()

fetch.predicate = NSPredicate(format: "customerName = %@", "\(customerName)")


var customer = [Customers]()
do {
customer = try viewContext.fetch(fetch)
} catch let error {
print(error.localizedDescription)
}
return customer
}

enter image description here

关于swift - 将实体数组保存在另一个实体下 CoreDataRelationships,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54938428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com