如何将阵列控制器绑定到核心数据模型? [英] How do I bind my Array Controller to my core data model?

查看:94
本文介绍了如何将阵列控制器绑定到核心数据模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是SWIFT编程的新手,正在尝试制作一个简单的应用程序,以学习使用核心数据并将其绑定以显示在应用程序中.我看了很多例子,但似乎都有些陈旧.我正在使用XCode 9.

I'm new to SWIFT programming and am trying to do a simple app to learn to use core data and bind it to display in an app. I've looked at loads of examples but all seem to be old. I am working in XCode 9.

我从带有Core Data的MacOS Cocoa应用开始.我有一个简单的实体,名为锻炼",具有4个属性,日期,秒,运动和rpe.

I started with a MacOS Cocoa app with Core Data. I have a simple entity called "Workout" with 4 attributes date, seconds, sport and rpe.

然后我在视图控制器场景下添加了一个数组控制器.我添加了一个Table视图,该视图将Array Controller设置为数据源.我添加了用于添加和删除按钮的链接,这些链接指向数组控制器的添加和删除方法.

I then added a Array Controller under the view controller scene. I added a Table view which set the Array Controller as the data source. I've added buttons to add and delete linking to array controllers add and remove methods.

我认为我现在要做的就是将阵列控制器绑定到我的核心数据模型的managedObjectContext.这可以在AppDelegate中找到.但是,当我选择阵列控制器"并转到绑定"并选择参数"时,绑定到的唯一选项是视图控制器"和共享用户默认控制器".我选择了View Controller,但无法找出要链接到我的数据模型的模型关键路径".

I think all I need to do now is to bind the Array Controller to the managedObjectContext of my Core Data Model. This is found in the AppDelegate. However when I select the Array Controller and go to Bindings and select Parameters the only options to bind to are "View Controller" and "Shared User Defaults Controller". I've selected View Controller but cannot figure out the Model Key Path to link in to my data model.

我觉得我肯定想念一些明显的东西.我觉得必须有一种方法可以绑定到AppDelegate或从视图控制器绑定到模型关键路径,但我也找不到.任何帮助,不胜感激.

I feel I must be missing something obvious. I feel there must either be a way to bind to the AppDelegate or a Model Key Path from the View Controller but I can't figure out either. Any help much appreciated.

推荐答案

在基于情节提要的项目中,没有从视图控制器到AppDelegate类的(绑定)引用.

In a storyboard based project there is no (binding) reference from a view controller to the AppDelegate class.

一种解决方案是在视图控制器中添加属性并覆盖init?(coder

A solution is to add a property and override init?(coder in the view controller

@objc let managedObjectContext: NSManagedObjectContext

required init?(coder: NSCoder) {
    self.managedObjectContext = (NSApp.delegate as! AppDelegate).persistentContainer.viewContext
    super.init(coder: coder)
}

然后将ManagedObjectContext绑定到ViewController-> managedObjectContext.

在阵列控制器的属性检查器中,不要忘记将Mode设置为Entity Name,插入实体名称并选中Prepares Content.

In the Attribute Inspector of the array controller don't forget to set the Mode to Entity Name, insert the entity name and check Prepares Content.

这篇关于如何将阵列控制器绑定到核心数据模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆