我正在设计一个购物应用程序,用户可以在其中添加目录中的新商品或修改购物车中的现有商品。
这是问题所在:将项目添加到cart
时,我将项目添加到两件事:cart
对象和realm
。我认为这种设计会造成很多冗余,因为我觉得我可以将项目添加到领域中,并在进行更改时使cart
进行动态更新,反之亦然。
关于如何构造代码以消除冗余的任何想法吗?
我的代码设计如下:
从目录:
@IBAction func addToCart(_ sender: UIBarButtonItem) {
let itemToAdd = product
let existingIndex = cart.containsAtIndex(product!)
// If item from catalogue exist in cart, then modify
if (existingIndex >= 0) {
cart.changeItem(existingIndex, newItem: itemToAdd!)
modifyCart(product: itemToAdd!)
}
// If item is not found in cart, then add a new one
else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let controller = storyboard.instantiateViewController(withIdentifier: "CartTableView") as? CartTableViewController {
let newIndexPath = IndexPath(row: cart.numberOfItems(), section: 0)
cart.addItem(itemToAdd!)
controller.tableView.insertRows(at: [newIndexPath], with: .automatic)
saveToCart(product: itemToAdd!, update: true)
}
}
self.navigationController?.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}
private func saveToCart(product: Product, update: Bool) {
let realm = try! Realm()
print(product)
try! realm.write {
realm.add(product, update: true)
}
}
private func modifyCart(product: Product) {
let prodName = product.itemName
let realm = try! Realm()
try! realm.write {
let item = realm.objects(Product.self).filter("itemName = %@", prodName).first
item!.quantity = product.quantity
}
}
购物车班级:
class Cart: NSObject {
static let myCart = Cart()
private var products: [Product]
private override init() {
self.products = []
}
func getCartItems() -> [Product] {
return products
}
func getItem(_ index: Int) -> Product? {
if products.indices.contains(index) {
return products[index]
} else {
return nil
}
}
func addItem(_ item: Product) {
products.append(item)
}
func removeItem(_ index: Int) {
products.remove(at: index)
}
func numberOfItems() -> Int {
return products.count
}
func changeItem(_ index: Int, newItem: Product) {
if products.indices.contains(index) {
products[index] = newItem
}
}
func containsAtIndex(_ item: Product) -> Int {
for i in (0..<products.count) {
if (products[i].itemName == item.itemName) {
return i
}
}
return -1
}
}