swift - 我无法让我的代码使用过时的 Swift Core Data 教程

标签 swift xcode core-data

首先,我对 XCode 还很陌生。我是一名正在上编码类(class)的高中生。

这是教程:https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial

您能帮我更新代码以适应新的 Swift 更新吗?

错误:“AppDelegate 类型的值没有管理对象上下文成员”

给我错误的行:

let appDelegate =
            UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext

但是,当我删除它并将其替换为

let delegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = delegate.persistentContainer.viewContext

弹出更多错误。

我的完整代码:

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource
{
    @IBOutlet weak var tableView: UITableView!

    @IBAction func addName(_ sender: Any)
    {
        let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .alert)

        let saveAction = UIAlertAction(title: "Save", style: .default, handler:
            {
                (action:UIAlertAction) -> Void in
                let textField = alert.textFields!.first
                self.saveName(name: textField!.text!)
                self.tableView.reloadData()
        })

        let cancelAction = UIAlertAction(title: "Cancel", style: .default) {
            (action: UIAlertAction) -> Void in
        }

        alert.addTextField
            {
                (textField: UITextField) -> Void in
            }

        alert.addAction(saveAction)
        alert.addAction(cancelAction)
        present(alert, animated: true, completion: nil)
    }

    func saveName(name: String)
    {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext

        let entity =  NSEntityDescription.entityForName("Person", inManagedObjectContext:managedContext)

        let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

        person.setValue(name, forKey: "name")

        do
        {
            try managedContext.save()
            people.append(person)
        }
        catch let error as NSError
        {
            print("Could not save \(error), \(error.userInfo)")
        }
    }

    var people = [NSManagedObject]()

    override func viewDidLoad()
    {
        super.viewDidLoad()
        title = "\"The List\""
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        //1
        let appDelegate =
            UIApplication.shared.delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext

        //2
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

        //3
        do {
            let results =
                try managedContext.executeFetchRequest(fetchRequest)
            people = results as! [NSManagedObject]
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }
    }

    func tableView(_ tableView: UITableView,
                   numberOfRowsInSection section: Int) -> Int {
        return people.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        let person = people[indexPath.row]

        cell!.textLabel!.text = person.value(forKey: "name") as? String

        return cell!
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

最佳答案

您可以使用一个简单的库(由我编写)来获取最新的 Swift 语法 AACoreData 。 安装库后只需分配您的数据模型即可,

AACoreData.sharedInstance().dataModel = "YourEntity"

有关更多指南和文档,请访问官方存储库 AACoreData .

关于swift - 我无法让我的代码使用过时的 Swift Core Data 教程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41799958/

相关文章:

iphone - 在没有 UITableViewController 的情况下使用 NSFetchedResultsController

swift - Collection View 中带有补充 View 的 tvOS 地标

ios - 在我的应用程序中点击 UITextField 时,UIKeyboard 不出现

ios - 自定义 UIView 类约束取决于 ParentView

objective-c - 对类实例的全局访问 - 最佳设计方法?

ios - 是否可以在没有 UITableView 的情况下从 Sqlite(和 CoreData)检索数据 - Swift 3

iphone - 如何从 View Controller 引用应用程序委托(delegate)中的 ManagedObjectContext?

swift - 为什么 type(of :) return Metatype, 而不是 T.Type?

ios - 如何在不滚动 SwiftUI 的情况下显示整个列表

iphone - 从格式为 "4/26/1980"的 NSString 中检索日或月 int