我正在使用CoreData的应用程序。保存和检索数字的问题
我是强大的数字并检索它们,但是当我存储多个字段时,它只显示数字的最后一个字段,但是在其他字段中显示为0。下面是我的代码。
来存储他们...
let CWConvert = Double(CWeight.text!)
storeTranscription18CW(pageText: (CWConvert)!, textFileUrlString: "cWeight")
savePlus += 1
let TWConvert = Double(TWeight.text!)
storeTranscription18TW(pageText: (TWConvert)!, textFileUrlString: "tWeight")
和...
func getContext() -> NSManagedObjectContext {
_ = UIApplication.shared.delegate as! AppDelegate
return DataController().managedObjectContext
}
func storeTranscription18CW (pageText: Double, textFileUrlString: String) {
let context = getContext()
//retrieve the entity that we just created
let entity = NSEntityDescription.entity(forEntityName: "TextInputs", in: context)
let transc = NSManagedObject(entity: entity!, insertInto: context)
// set the entity values
transc.setValue(pageText, forKey: "cWeight")
//save the object
do {
try context.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
func storeTranscription18TW (pageText: Double, textFileUrlString: String) {
let contexta = getContext()
//retrieve the entity that we just created
let entitya = NSEntityDescription.entity(forEntityName: "TextInputs", in: contexta)
let transc = NSManagedObject(entity: entitya!, insertInto: contexta)
// set the entity values
transc.setValue(pageText, forKey: "tWeight")
//save the object
do {
try contexta.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
,并以检索。
func getTranscriptions18CW() {
//create a fetch request, telling it about the entity
let fetchRequesta: NSFetchRequest<TextInputs> = TextInputs.fetchRequest()
do {
//go get the results
let searchResults18CW = try getContext().fetch(fetchRequesta)
for transa in searchResults18CW as [NSManagedObject] {
if let resulta = transa.value(forKey: "cWeight") {
if let stra = resulta as? String {
CWeight.text = stra
}else {
CWeight?.text = "\(resulta)"
}
}
}
//get the Key Value pairs (although there may be a better
}catch {
print("Error with request: \(error)")
}
}
func getTranscriptions18TW() {
//create a fetch request, telling it about the entity
let fetchRequest: NSFetchRequest<TextInputs> = TextInputs.fetchRequest()
do {
//go get the results
let searchResults18TW = try getContext().fetch(fetchRequest)
for trans in searchResults18TW as [NSManagedObject] {
if let result = trans.value(forKey: "tWeight") {
if let str = result as? String {
TWeight.text = str
}else {
TWeight?.text = "\(result)"
}
}
//get the Key Value pairs (although there may be a better way to do that...
}
}catch {
print("Error with request: \(error)")
}
}
我已经尝试不同的名称,但得到相同的只显示最后一个为实数,如果我时刻了最后一个,则第一个显示的实际价值。
那么你想显示tWeight的多个值到同一个文本字段?这是在一个tableview? – MwcsMac
嗨,没有这是2个不同的文本字段,当我把它们设置为核心数据中的字符串,并设置任何而不是双重然后它的工作原理,但我需要它们是双重因为我想转换数学来数字 –
为什么你没有同一个保存功能中的两个号码?当您保存为两个不同的功能时,为每次保存创建一个新行。因此,当您保存当前体重3时,Target将被保存为零。保存目标时会发生同样的事情。 – MwcsMac