所以,我正在努力学习如何正确处理CoreData。
这是我的代码:
import UIKit
import CoreData
class IngredientsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var fetchedResultsController: NSFetchedResultsController?
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchIngredients(), managedObjectContext: moc!, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController?.delegate = self
fetchedResultsController?.performFetch(nil)
}
func fetchIngredients() -> NSFetchRequest {
var fetchRequest = NSFetchRequest(entityName: "DetailsForRecipe")
let sortDescriptor = NSSortDescriptor(key: "ingredients", ascending: true)
fetchRequest.predicate = nil
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchBatchSize = 20
return fetchRequest
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController?.sections?[section].numberOfObjects ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ingCell", forIndexPath: indexPath) as! UITableViewCell
if let ingCell = fetchedResultsController?.objectAtIndexPath(indexPath) as? DetailsForRecipe {
cell.textLabel?.text = ingCell.ingredients
}
return cell
}
}
和
import UIKit
import CoreData
class SingleIngredientViewController: UIViewController {
@IBOutlet var ingField: UITextField!
var moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func addIng(sender: AnyObject) {
let entityDescription = NSEntityDescription.entityForName("DetailsForRecipe", inManagedObjectContext: moc!)
let details = DetailsForRecipe(entity: entityDescription!, insertIntoManagedObjectContext: moc)
details.ingredients = ingField.text
var error: NSError?
moc?.save(&error)
if let err = error {
var status = err.localizedFailureReason
println(status)
} else {
println("Ingredient \(ingField.text) saved successfully!")
}
if let navigation = navigationController {
navigation.popViewControllerAnimated(true)
}
}
}
我的模特:
import Foundation
import CoreData
class DetailsForRecipe: NSManagedObject {
@NSManaged var name: String
@NSManaged var ingredients: String
@NSManaged var image: NSData
}
应用程序应在文本字段中插入成分名称,将其保存到coreData中,然后应在表格视图中检索它。当我给成分名称发短信并按"添加"时,prinln消息显示已成功保存,但表格视图不会更新。
我在这里做错了什么?我不是开发人员,我已经阅读了很多有关如何执行此操作的教程,但这非常令人困惑!所以原谅我这个。 提前谢谢!
答案 0 :(得分:1)
我还没有阅读完整的源代码,但通过立即看一眼,我没有看到你调用了tableview的reloadData
函数。如果您没有为表格视图设置IBOutlet,则需要执行此操作,然后在其上调用reloadData()
。
答案 1 :(得分:0)
完成更改后,在表格视图上调用reloadData()
。