简体   繁体   English

开始使用Core Data

[英]Getting started with Core Data

I am having trouble understanding how Core Data works conceptually and in terms of code. 我无法理解Core Data在概念和代码方面的工作原理。

I get that there is a coordinator and a context. 我知道有一个协调员和一个上下文。 I also get that there is state management. 我也知道有国家管理。 How do they work together? 他们如何一起工作?

I don't understand how I can store, say, an image and a few strings as an object. 我不明白如何将图像和一些字符串存储为对象。

Let's say I want to retrieve the image and the strings later. 假设我想稍后检索图像和字符串。 What do I do? 我该怎么办?

Where do I save my state? 我在哪里保存我的州? How? 怎么样?

What does my code look like? 我的代码是什么样的? I would really appreciate a bare-bones code sample here, because I'm really confused. 我真的很感激这里的一个简单的代码示例,因为我真的很困惑。

These are some of the best tutorials I've found: 这些是我发现的一些最好的教程:

As for your quesstions: 至于你的问题:

I get that there is a coordinator and a context. 我知道有一个协调员和一个上下文。 I also get that there is state management. 我也知道有国家管理。 How do they work together? 他们如何一起工作?

The persistent store coordinator is what manages the place your data is actually being stored, be that a SQLlite DB or a XML file or whatever. 持久性存储协调器管理您的数据实际存储的位置,即SQLlite DB或XML文件或其他。 The coordinator is the abstraction so you don't have to worry about what type of storage is in the backend. 协调器是抽象的,因此您不必担心后端的存储类型。

The Managed Object Context is how you interact with the Persistent Store Coordinator. 托管对象上下文是您与持久性存储协调器交互的方式。 Think of it as your scratch pad. 把它想象成你的便笺簿。 You create and modify Managed Objects from the Managed Object Context. 您可以从托管对象上下文创建和修改托管对象。

I don't understand how I can store, say, an image and a few strings as an object. 我不明白如何将图像和一些字符串存储为对象。 Let's say I want to retrieve the image and the strings later. 假设我想稍后检索图像和字符串。 What do I do? 我该怎么办?

If you look through some of the above tutorials, you'll see how to pull objects out of the managed object context. 如果您查看上面的一些教程,您将看到如何从托管对象上下文中提取对象。 A NSString would simply be stored as a string attribute on a managed object, like so: NSString只是作为字符串属性存储在托管对象上,如下所示:

[managedObject setValue:@"TestString" forKey:@"SomeStringProperty"];

I'm not quite sure about images as I've never stored an image in Core Data before. 我对图像不太确定,因为我之前从未在Core Data中存储过图像。 I know anything that can be serialized can be stored as a transformable attribute. 我知道任何可以序列化的东西都可以存储为可转换的属性。 Here's a post about storing UIImages in Core Data 这是一篇关于在核心数据中存储UIImages的帖子

Where do I save my state? 我在哪里保存我的州? How? 怎么样?

You simply call the 'save' method on your managed object context. 您只需在托管对象上下文中调用“save”方法即可。 Like so: 像这样:

[context save:&error]

浏览Apple的核心数据教程

文档 代码可从苹果,让你开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM