CoreData 简单使用

0.0 coredata 相关术语及简介,

coredata 结构图

1.查看运行时的sql语句,在Product-Scheme-Edit Scheme-Run-Arguments-Arguments Passed On Launch,添加;

a,   -com.apple.CoreData.SQLDebug

b.  1

Run-Arguments-Arguments Passed On Launch



2.创建coreData

2.1,创建entity,并且添加属性attributes,

2.2 创建2个ENTITY,并且添加属性attributes,

2.2.5 设置Relationships,关联两张表,

2.2.5.2. Relationships 建立表联系

2.2.5.3. object graph

2.2.5.4.设置inverse 



2.3.新建Core Data - NSManagedObject subclass

2.4.同时选两个

2.5.生成八个文件

8个文件(这是两张表)

2.9.1,添加按钮及事件

2.9.2 按钮点击方法,

3,增 可以在方法里面就传入需要增加的数据

4.1.删除 指定条件数据 设置NSPredicate 删除之后要保存删除后的结果 app.managedObjectContext save:

4.2 删除所有数据 删除之后要保存删除后的结果 app.managedObjectContext save:

5.1.查找 指定条件的数据 设置NSPredicate request.predicate是一个数组,也就是说可以可以设置多个条件

5.2.查找  所有数据 返回的是数组

6,改,可以传入指定参数进行查找 并且同时传入修改后的数据 设置NSPredicate查找,修改后要保存,app.managedObjectContext save:

*appendix*

Core Data From Scratch:Data Model


This post is part of a series called Core Data from Scratch.

Core Data from Scratch: Core Data Stack

Core Data from Scratch: Managed Objects and Fetch Requests

Introduction

In the first article of this series, we learned about the Core Data stack, the heart of a Core Data application. We explored the managed object context, the persistent store coordinator, and the managed object model.

This article focuses on the data model of a Core Data application. We zoom in on Xcode's data model editor and we take a look at entities, attributes, and relationships.

1. Data Model Editor

Start by downloading the project from the previous tutorial or clone the repository from GitHub. Open the project in Xcode and, in the Project Navigator, search for Core_Data.xcdatamodeld. Xcode automatically shows the data model editor when the project's data model is selected.

2. Entities

Before we explore the editor's user interface, we need to create an entity to work with. At the bottom of the data model editor, click the Add Entity button. This will add an entity with name Entity. It will show up in the Entities section on the left of the data model editor. Change the entity's name to Person by double-clicking it in the Entities section.

"What is an entity?" you may be wondering. To bring back the database analogy, an entity is comparable to a table in a database. When you select the Person entity, you see that an entity can have attributes, relationships, and fetched properties. Don't worry about fetched properties for now, they're a more advanced feature of the framework.

3. Attributes

Give the Person entity an attribute by clicking the plus button at the bottom of the Attributes table. Double-click the attribute's name and set it to first. From the Type drop-down menu, select String. If we compare this to a table in a database, the Person table now has a column first of type String.

Even though I don't want to confuse you by comparing entities with tables of a database, it makes it easier to understand what entities and attributes are. In fact, if you use a SQLite database as the backing store of your application, Core Data will create a table for you to store the data of the Person entity. However, this is something we don't have to and should not need to worry about. Remember that Core Data is not a database.

The same goes for relationships. How Core Data keeps track of relationships is something we don't need to worry about. In fact, Core Data makes sure relationships are only loaded when the application needs them. This is something we'll revisit later in this series.

Add two more attributes to the Person entity, last of type String and age of type Integer 16. The type you choose for numbers is not important at this point. It tells Core Data how it should structure the database and optimize for performance.

Attribute Options

The attribute of an entity can be configured through the Data Model Inspector. Select the first attribute of the Person entity and open the inspector on the right. The Data Model Inspector lets you configure the selected attribute. At this point, we're only interested in a few settings, Optional, Attribute Type, and Default Value.

Optional

Marking an attribute as optional means that the attribute can be empty or left blank for a record. In our example, however, we want to make sure every Person record has a first name. With the first attribute selected, uncheck Optional to mark it as required. New attributes are optional be default.

Marking an attribute as required has consequences though. If we save a Person record without a valid first name, Core Data will throw an error. This means that we need to make sure that the record's first attribute is set before saving it.

Attribute Type

The attribute type is important for several reasons. It tells Core Data in what format it should save the attribute and it will also return the attribute's data to us in the specified format. Each attribute type has a different set of configuration options. Change the attribute type of the first attribute to Date to see the configuration options for an attribute of type Date.

Default Value

Several attribute types, such as String and Date, have a Default Value field you can set. This is convenient, for example, if an attribute is required and you want to ensure the attribute for a record has a valid value when it's inserted in the database.

Note that the default value is only used when a new record is created. If an existing Person record, for example, is updated by setting the first attribute to nil, then Core Data won't populate the first attribute with the default value. Instead Core data would throw an error, because we marked the first attribute as required.

4. Relationships

Core Data really shines when you start working with relationships between entities. Let's see how this works by adding a second entity named Address. The Address entity has four attributes of type String, street, number, city, and country.

Relationship between entities have a number of defining characteristics, the name, the destination, the cardinality of the relationship, the inverse relationship, and the relationship's delete rule.

Let's explore relationships in more detail by creating a relationship between the Person and Address entities.

Name, Destination, and Optionality

Create a relationship by selecting the Person entity and clicking the plus button at the bottom of the Relationships table. Name the relationship address and set the Destination to the Address entity. This indicates that each person record can be associated with an address record.

As with attributes, relationships are optional by default. This means that no validation error will be thrown if a person record has no relationship with an address record. Let's change this by unchecking the Optional checkbox in the Data Model Inspector on the right.

Inverse Relationship

At the moment, the person can have a relationship with an address record. However, if the person has an address record associated with it, the address record does not know about the person record, because the relationship is uni-directional at the moment—from Person to Address. Most relationships in Core Data, however, are bi-directional, both entities know about the relationship.

Let's create the inverse relationship from the Address entity to the Person entity by selecting the Address entity and creating a relationship named person with the Person entity as its destination.

Even though we created the inverse relationship between Address and Person, Xcode gives us a few warnings telling us Person.address should have an inverse and Address.person should have an inverse. Did we do something wrong?

Core Data isn't clever enough to know which relationship is the inverse relationship of which relationship. This is easy to fix though. Select the Person entity and set the Inverse of the address relationship to person, the person relationship. If you now select the Address entity, you'll see that the inverse of the address relationship has already been set to the person relationship for you.

Data Model Graph

When the data model gains in complexity, relationships can become confusing and unclear. Xcode has your back covered though. The data model editor has two styles, table and graph. In the bottom right of the editor, you'll see a toggle that lets you switch between the two modes. Click the left button to switch to the graph style.

The graph style shows you the object graph we've created so far. It shows us the entities we've created, their attributes, and their relationships. One of the most useful feature, however, is the visual representation of the relationships between the data model's entities. A line with an arrow at each end connects Person and Address, signifying their bi-directional relationship.

To-Many Relationships

The relationships we've created so far are to-one relationships, a person can have one address and vice versa. However, it's perfectly possible that several people live at the same address. How would we include this extra information in our data model?

A relationship's cardinality specifies if it's a to-one or to-many relationship. Let's change the person relationship of the Address entity to make it a to-many relationship. Select the person relationship of the Address entity, change its name to persons to reflect the to-many relationship, and set the relationship Type to To Many in the inspector on the right.

The name of the relationship isn't important, but it shows that its a to-many relationship. Did you notice that the data model graph updated as well? The relationship endpoint to the Person entity has two arrows to signify the to-many nature of the relationship.

Many-To-Many Relationships

Wait a minute. Isn't it possible that a person is associated with more than one address. A person can have a work address and a home address. Right? Core Data solves this by creating a many-to-many relationship. Select the address relationship of the Person entity, change its name to addresses, and set the relationship Type to To Many. The data model editor shows the updated relationship as a line with two arrows at each end.

Reflexive Relationships

The way Core Data implements relationships is very flexible. The destination entity of a relationship can even be the same as the source entity. This is known as a reflexive relationship. It's also possible to have multiple relationships of the same type with different names. A person, for example, can have a mother and a father. Both relationships are reflexive with the only difference being the name of the relationship.

Delete Rules

What happens when the record on one end of the relationship is deleted? If you were to think about Core Data as a database, then the answer would be obvious. Core Data, however, isn't a database.

Assume you have an Account entity with a to-many relationship to a User entity. In other words, an account can have many users and each user belongs to one account. What happens when you delete a user? What happens when you delete an account? In Core Data, each relationship has a delete rule that makes it clear what happens in these situations.

Delete rules make sure you don't have to worry about explicitly updating the backing store when a record is deleted. Core Data takes care of this to ensure the object graph remains in a consistent state.

Select  the addresses relationship of the Person entity and open the inspector on the right. The Delete Rule menu has four options, No Action, Nullify, Cascade, and Deny.

No Action

If you select No Action, Core Data doesn't update or notify the source record of the relationship. This means that the source record of the relationship still thinks it has a relationship with the record that was deleted. Note that this is rarely what you want.

Nullify

This option sets the destination of the relationship to null when the destination record is deleted. This is the default delete rule of a relationship.

Cascade

If the relationship from Person to Address is set to Cascade, deleting a person record will also delete any address records that are associated with the person record. This is useful, for example, if a relationship is required and the record cannot or shouldn't exist without the relationship. A user, for example, shouldn't exist if it's not associated with an account.

Deny

In a sense, Deny is the inverse of Cascade. For example, if we have an Account entity that has a to-many relationship with a User entity with its delete rule set to Deny, an account record can only be deleted if it has no user records associated with it. This ensures that no user records exist without an account record. The result is similar to the Cascade delete rule, but the implementation differs.

Conclusion

In this tutorial, we've taken a closer look at the data model used by a Core Data application. You should now be familiar with entities, attributes, and relationships, and you should be able to create them using Xcode's data model editor.

Core Data is very good at managing relationships and Xcode's data model editor makes it easy to create and manage relationships between entities. Relationships between entities are powerful and easily configurable. Delete rules ensure that the object graph Core Data manages remains healthy and in a consistent state.

In the next article, we get our hands dirty and start working with Core Data. You'll learn how to create, read, update, and delete records, and become familiar with NSManagedObject and NSFetchRequest.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容