我正在使用Swift编写一个iOS应用程序,遵循Youtube上的教程。该应用程序将具有与待办事项列表应用程序相同的功能,但另一种用途。但是,当我希望保存数据(并在调试器中打印)时,没有任何反应。我做错了什么?
@IBAction func saveTapped(sender: AnyObject) {
println("SaveTapped")
// Reference to our app delegate
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
// Reference moc
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("Tankningslista", inManagedObjectContext: contxt)
// Create instance of our data model and initialize
var nyTankning = Model(entity: en!, insertIntoManagedObjectContext: contxt)
// Map our properties
nyTankning.liter = (textFieldLiter.text as NSString).floatValue
nyTankning.kronor = (textFieldKronor.text as NSString).floatValue
nyTankning.literpris = (textFieldLiterpris.text as NSString).floatValue
//nyTankning.datum = datePickerDatum.date
// Save our context
contxt.save(nil)
println(nyTankning) //HERE I ESPECT THE DATA TO BE PRINTED IN THE DEBUG WINDOW
// navigate back to root vc
self.navigationController?.popToRootViewControllerAnimated(true)
}
答案 0 :(得分:0)
您需要先获取数据才能显示。现在你只保存它。保存数据后,请在代码中查看我的添加内容。
@IBAction func saveTapped(sender:AnyObject){ 的println( “SaveTapped”)
// Reference to our app delegate
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
// Reference moc
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("Tankningslista",inIntoManagedObjectContext: contxt)
// Create instance of our data model and initialize
// Use your NSManagedModel to initialize not only the Model Keyword!
var nyTankning = Tankningslista(entity: en!, insertIntoManagedObjectContext: contxt)
// Map our properties
nyTankning.liter = (textFieldLiter.text as NSString).floatValue
nyTankning.kronor = (textFieldKronor.text as NSString).floatValue
nyTankning.literpris = (textFieldLiterpris.text as NSString).floatValue
//nyTankning.datum = datePickerDatum.date
// Save our context
if contxt.save(nil) {
// Fetch the Data from Core Data first....
let fetchRequest = NSfetchRequest(entityName: "Tankningslista")
var error:NSError?
var result = contxt.executeFetchRequest(fetchRequest, error: &error) as [Tankningslista]
for res in result {
// Now you can display the data
println(res.liter)
......
......
}
// End of the fetching
} else {
println(error)
}
//println(nyTankning) //HERE I ESPECT THE DATA TO BE PRINTED IN THE DEBUG WINDOW
// navigate back to root vc
self.navigationController?.popToRootViewControllerAnimated(true)
我希望解决方案可以解决您的问题。
答案 1 :(得分:0)
Puuh,有很多需要改进的地方,我真的建议你选择一个真实的"在Udemy / Bitfountain或Udacity等平台上的iOS / swift课程。首先,你需要在一个函数中获取ManagedObject(然后将结果存储在一个数组中)或者使用NSFetchedResultController(它主要用于带有TableViews的CoreData)然后我不确定你的numberOfRowsInSection函数中有什么,在这里你也应该有正确的返回值。正如我所说,要解决这个问题真的太多了......