获取数组的总和,保存到核心数据,并在应用程序重新打开后从总和开始



我有点拘泥于我认为是一个简单的解决方案,我就是不知道该怎么办。

我基本上是在为iOS创建一个费用应用程序,我已经到了需要将UITableView列表中的所有总费用相加的地步。

private var items:[Shoe] = []
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
private var managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Start of calculating the gain or loss for the individual item
let buyDouble: Double? = Double(buyToSave)
let sellDouble: Double? = Double(sellToSave)
let feeDouble: Double? = Double(feeToSave)
let feeInt = 1-(feeDouble!/100)
let profit = (feeInt*sellDouble!) - buyDouble!
let profitNSNumb = profit as NSNumber
let profitString = currencyFormatter.string(from: profitNSNumb)
let shoe = Shoe(entity: Shoe.entity(), insertInto: self.managedContext)
shoe.name = nameToSave
shoe.buyPrice = buyToSave
shoe.sellPrice = sellToSave
shoe.size = sizeToSave
shoe.fee = feeToSave
shoe.profitLoss = profitString
shoe.quantity = Int16(shoeQuantity)
shoe.sum = shoe.sum + profit
// Save the data
self.appDelegate.saveContext()
// Reloads the UITableView
self.shoeList.reloadData()
self.viewDidLoad()

我相信我的逻辑是正确的,对吧?我不知道为什么每次退出应用程序并重新打开它时,我都会保持0美元的起步价?

例如:

项目#。。。。。。。费用

项目1……..$100

第2项…….200美元

第3项…….50美元

总费用:$350

然后当我关闭应用程序并重新启动时:

项目#。。。。。。。费用

项目1……..$100

第2项…….200美元

第3项…….50美元

费用总额:350美元<----我希望它的起价是350美元,而不是0美元

您必须在上下文中调用.save((才能保存所做的更改(在本例中创建了一个新的Shoe对象(。

试着这样保存:

do {          
try self.managedContext.save()       
} catch {       
print("Failed saving")
}

相关内容