【发布时间】:2015-07-29 02:13:55
【问题描述】:
所以,我正在努力学习如何正确处理 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 消息说它已成功保存,但表格视图没有更新。
我在这里做错了什么?我不是开发人员,我已经阅读了很多关于如何做到这一点的教程,但这非常令人困惑!所以请原谅我。 提前致谢!
【问题讨论】:
标签: ios swift core-data save nsfetchrequest