我能';我不能让我的代码与过时的Swift核心数据教程一起使用

我能';我不能让我的代码与过时的Swift核心数据教程一起使用,swift,xcode,core-data,Swift,Xcode,Core Data,首先,我对XCode很陌生。我是一个上编码课的高中生 以下是教程: 你能帮我更新代码以适应新的Swift更新吗 错误:“AppDelegate类型的值没有成员managedObjectContext” 给我错误的行: let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext 但是,当我删

首先,我对XCode很陌生。我是一个上编码课的高中生

以下是教程:

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

错误:“AppDelegate类型的值没有成员managedObjectContext”

给我错误的行:

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.
    }
}
导入UIKit
导入CoreData
类ViewController:UIViewController、UITableViewDataSource
{
@IBVAR表格视图:UITableView!
@iAction func addName(\发送方:任意)
{
let alert=UIAlertController(标题:“新名称”,消息:“添加新名称”,首选样式:。警报)
让saveAction=UIAlertAction(标题:“保存”,样式:。默认值,处理程序:
{
(操作:UIAlertAction)->在中无效
让textField=alert.textFields!。首先
self.saveName(名称:textField!.text!)
self.tableView.reloadData()
})
让cancelAction=UIAlertAction(标题:“取消”,样式:。默认值){
(操作:UIAlertAction)->在中无效
}
alert.addTextField
{
(textField:UITextField)->中的Void
}
alert.addAction(saveAction)
alert.addAction(取消操作)
当前(警报、动画:真、完成:无)
}
func saveName(名称:字符串)
{
让appDelegate=UIApplication.shared.delegate为!appDelegate
让managedContext=appDelegate.managedObjectContext
让entity=NSEntityDescription.entityForName(“Person”,在ManagedObjectContext:managedContext中)
让person=NSManagedObject(实体:entity!,插入ManagedObject上下文:managedContext)
person.setValue(名称,forKey:“名称”)
做
{
请尝试managedContext.save()
people.append(person)
}
将let错误捕获为NSError
{
打印(“无法保存\(错误),\(错误.用户信息)”)
}
}
var people=[NSManagedObject]()
重写func viewDidLoad()
{
super.viewDidLoad()
title=“\”列表“
tableView.register(UITableViewCell.self,强制重用标识符:“单元格”)
//加载视图后,通常从nib执行任何其他设置。
}
覆盖函数视图将出现(uo动画:Bool){
超级。视图将显示(动画)
//1
让appDelegate=
UIApplication.shared.delegate作为!AppDelegate
让managedContext=appDelegate.managedObjectContext
//2
let fetchRequest=NSFetchRequest(entityName:“Person”)
//3
做{
让结果=
请尝试managedContext.executeFetchRequest(fetchRequest)
人员=结果为![NSManagedObject]
}将let错误捕获为NSError{
打印(“无法获取\(错误),\(错误.userInfo)”)
}
}
func tableView(tableView:UITableView,
numberOfRowsInSection部分:Int)->Int{
返回人。计数
}
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell
{
let cell=tableView.dequeueReusableCell(带标识符:“cell”)
让person=people[indexPath.row]
cell!.textlab!.text=person.value(forKey:“name”)作为?字符串
返回单元!
}
重写函数didReceiveMemoryWarning()
{
超级。我收到了记忆警告()
//处置所有可以重新创建的资源。
}
}

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

AACoreData.sharedInstance().dataModel = "YourEntity"

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

您应该使用更新的Swift 3核心数据模型教程-这比艰难地转换旧代码更容易


请将您收到的错误添加到您的帖子中,我已经更新了!还请包括您的AppDelegate.swift文件的内容,并描述垂直弹出的“更多错误”,但您可以了解更多事情是如何艰难工作的;-)