Swift利用CoreData如何存储多种数据类的通讯录

2020-01-08 23:59:11王旭

前言

我们在上一篇文章简单的实现了一个通讯录,说是通讯录实际上就只是一个简简单单的Name List。这次我们要往这个通讯录里面加入更多的元素,目的也是为了学习CoreData如何存储更多的数据类型。下面话不多说了,来随着小编一起看看详细的介绍吧。

完成后的效果:

swift,coredata,使用,coredata教程

1. CoreData支持存储数据类型

swift,coredata,使用,coredata教程

咦?这里面有两个好像很少看到的类型:Binary Data、Decimal、Transformable。这些都是神马东西?

1.1 Binary Data

顾名思义,就是二进制数据。对应到OC中就是NSData, Swift里面就是Data数据类型。

我们这次就试试在通讯里面存储一下图片,把图片变成Binary Data进行存储。

1.2 Decimal

Decimal为SQL Server、MySql等数据库的一种数据类型,不属于浮点数类型,可以在定义时划定整数部分以及小数部分的位数。使用精确小数类型不仅能够保证数据计算更为精确,还可以节省储存空间。

Decimal(n,m)表示数值中共有n位数,其中整数n-m位,小数m位。例:decimal(10,6),数值中共有10位数,其中整数占4位,小数占6位。

问题来了,Decimal(2,1):

1, 插入数据“12”会怎样?

会出现数据移除的错误。

2, 插入”1.2345“会怎样?

会自动四舍五入成1.2

3, 插入2,会怎样?

会自动补充成2.0,以确保2位的有效长度和1位的小数。

1.3 Transformable

这个类型就比较搞了,有人说它是万能类型,有人说它只要是对象就都可以。

在官方文档里面,Core Data Release Notes for OS X v10.5 是这么介绍的:

Transformable Attributes
There's a new "transformable" type for NSManagedObject attributes that allows you more easily support attribute types that Core Data doesn't support natively. You access an attribute as a non-standard type, but behind the scenes Core Data uses an instance of NSValueTransformer to convert the attribute to and from an instance of NSData. Core Data then stores the data instance to the persistent store.

If you don't specify a transformer, transformable attributes to use keyed archiving (NSKeyedUnarchiveFromDataTransformerName).

For more details, see Non-Standard Persistent Attributes.

说到底,这是一个非标准的类型。在中文中,非典型技术宅胖其实觉得翻译成“其他”类型更贴切。哈哈~~就和有关部门一样d=====( ̄▽ ̄*)b厉害。