如何使用Core Data访问和使用实体 [英] How do I access and use an entity using Core Data

查看:92
本文介绍了如何使用Core Data访问和使用实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在是时候使用核心数据 ,但开放的文档和指南在那里花了很多时间谈论一般设置和nitty粗砂幕后的细节。这些事情很重要,但我会喜欢一个快速,干净的来源,显示如何实际使用存储在Core Data模型中的信息。



场景



在我的简单示例中,我有一个实体类型:

  Job 
- salary [Double]
- dateCreated [Date]

是一个由故事板驱动的Swift iOS应用程序,默认生成的AppDelegate.swift处理我的托管对象上下文的生成。



问题



如何在我的应用程序中使用作业实例?


Bonus points if you can also provide insight about these items:




  • 作为习惯于MVC设计模式的人,如何避免在我的控制器内部包含脏数据访问,而不应用iOS开发最佳做法?

  • 如何从Core Data访问实体,同时遵循 DRY

  • 如何在方法和控制器之间传递管理对象, / li>

核心数据文档提供一些代码片段。这个问题本质上是询问这个逻辑在iOS应用程序中的位置,以及如何在抓取记录之后实际与抓取的记录进行交互。



示例



此问题并不意味着是一个广泛的,彻底的问题,所以我将尝试使用Core Data。在我的例子中,我有一个单一的UIViewController有一个标签。我想要此标签显示工作的工资。

  import UIKit 
import CoreData

class JobViewController:UIViewController {

@IBOutlet var salaryLabel:UILabel!
let managedObjectContext =(UIApplication.sharedApplication()。delegate as AppDelegate).managedObjectContext

func updateLabel(){
var job = getCurrentJob()
salaryLabel.text = job.salary //错误
}

func getCurrentJob() - >(???){
var error:NSError?
if let fetchedResults = managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName:Job),error:& error){
return fetchedResults [0]
}
}
$ b override func viewDidLoad(){
super.viewDidLoad()
}

override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning b $ b}
}

此示例不会编译,有两个原因:


  1. 我没有为getCurrentJob指定返回类型,因为我不确定要返回什么类型。

  2. 具有ERRORS的行试图访问 salary 属性,将会错误,因为没有办法知道salary是job的实际属性。

如何传递和使用作业对象?

解决方案

上述示例中缺少的关键字是 NSManagedObject子类,在Swift中, @NSManaged Swift注释。 NSManagedObject是一个通用类,以其最简单的形式,可以扩展为简单地提供对Core Data实体的属性的访问,但实际上这是传统模型逻辑应该存在的地方。



创建NSManagedObject子类



您可以通过查看Core Data模型并使用菜单命令自动生成这些对象: code> Editor->创建NSManagedObject子类。



这将生成 Job.swift (或您的实体名称)

  import Foundation 
import CoreData

class Job:NSManagedObject {

@NSManaged var dateCreated:NSDate
@NSManaged var salary:NSNumber

}



使用NSManagedObject子类



以供使用,您可以相应地转换获取的结果!完成后,以下是以前破碎的示例的更新版本

  import UIKit 
import CoreData

class JobViewController:UIViewController {

@IBOutlet var salaryLabel:UILabel!
let managedObjectContext =(UIApplication.sharedApplication()。delegate as AppDelegate).managedObjectContext

func updateLabel(){
var job:Job = getCurrentJob()
salaryLabel .text = job.salary //错误
}

func getCurrentJob() - > Job {
var error:NSError?
if let fetchedResults = managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName:Job),error:& error){
return fetchedResults [0]
}
}

override func viewDidLoad(){
super.viewDidLoad()
}

override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning b $ b}
}


It's time to use Core Data, but the open documentation and guides out there spend a lot of time talking about general setup and nitty gritty "behind the scenes" details. Those things are important, but I would love a quick, clean source showing how to actually use information stored in a Core Data model.

The Scenario

In my simple example I have a single entity type:

Job
 - salary [Double]
 - dateCreated [Date]

This is a Swift iOS app powered by story boards, with the default generated AppDelegate.swift which handles the generation of my Managed Object Context.

The Question

How do I use Job instances in my application?

Bonus points if you can also provide insight around these items:

  • As someone who is used to the MVC design pattern, how do I avoid including dirty data access inside of my controllers without bucking iOS development best practices?
  • How can I access entities from Core Data while following DRY?
  • How do I pass managed objects between methods and controllers while maintaining their type?

The Core Data documentation provides some snippets for fetching records. This question is essentially asking where that logic belongs in an iOS application, and how to actually interact with the fetched records after fetching them.

An Example

This question isn't meant to be a broad, sweeping question so I will ground it in an example attempt to use Core Data. In my example I have a single UIViewController which has a label. I want this label to show the salary from a job.

import UIKit
import CoreData

class JobViewController: UIViewController {

    @IBOutlet var salaryLabel: UILabel!
    let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext

    func updateLabel() {
        var job = getCurrentJob()
        salaryLabel.text = job.salary // ERRORS
    }

    func getCurrentJob()->(???) {
        var error: NSError?
        if let fetchedResults = managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName:"Job"), error: &error) {
            return fetchedResults[0]
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

This example will not compile for two reasons:

  1. I didn't specify a return type for getCurrentJob, since I wasn't sure what type to return
  2. The line with "ERRORS", which tries to access the salary attribute, will error because there is no way of knowing that salary is an actual attribute of job.

How do I pass around and use the job object?

解决方案

The key missing piece from the above example are NSManagedObject subclasses, and in Swift, the @NSManaged Swift annotation. NSManagedObject is a generic class which, in its most simple form, can be extended to simply provide access to attributes of a Core Data entity, but in reality this is where traditional model logic should live.

Creating NSManagedObject Subclasses

You can automatically generate these objects by viewing the Core Data model, and using the menu command: Editor->Create NSManagedObject Subclass.

This will generate Job.swift (or whatever your entity name is)

import Foundation
import CoreData

class Job: NSManagedObject {

    @NSManaged var dateCreated: NSDate
    @NSManaged var salary: NSNumber

}

Using NSManagedObject Subclasses

Your new class is now available for use, and you can typecast the fetched result accordingly! For completion, here's the updated version of the previously broken example

import UIKit
import CoreData

class JobViewController: UIViewController {

    @IBOutlet var salaryLabel: UILabel!
    let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext

    func updateLabel() {
        var job:Job = getCurrentJob()
        salaryLabel.text = job.salary // ERRORS
    }

    func getCurrentJob()->Job {
        var error: NSError?
        if let fetchedResults = managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName:"Job"), error: &error) {
            return fetchedResults[0]
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

这篇关于如何使用Core Data访问和使用实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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