如何将数组保存到 CoreData? [英] How to save Array to CoreData?

查看:47
本文介绍了如何将数组保存到 CoreData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将我的数组保存到 Core Data.

let array = [8, 17.7, 18, 21, 0, 0, 34]

该数组中的值以及值的数量是可变的.

1.我在 NSManagedObject 类中声明了什么?

class PBOStatistics: NSManagedObject, Equatable {@NSManaged var 日期:NSDate@NSManaged var 平均值:NSNumber@NSManaged var historyAverage: NSNumber@NSManaged var 总计:NSNumber@NSManaged var historyTotal: NSNumber@NSManaged var ordersCount: NSNumber@NSManaged var historyOrdersCount: NSNumber@NSManaged var values: [Double]//可以吗?@NSManaged 变量位置:PBLocation}

2.我在 .xcdatamodel 中声明了什么?

3.如何将其保存在我的实体中?(我使用 MagicalRecord)

let statistics = (PBOStatistics.MR_createInContext(context) as!PBOStatistics)statistics.values = [8, 17.7, 18, 21, 0, 0, 34]//够了吗?

解决方案

好的,我做了一些研究和测试.使用 Transformable 类型,解决方案很简单:

1.我在 NSManagedObject 类中声明了什么?

@NSManaged var values: [NSNumber]//[Double] 也有效

2.我在 .xcdatamodel 中声明了什么?

Transformable 数据类型.

3.如何将其保存在我的实体中?

statistics!.values = [23, 45, 567.8, 123, 0, 0]//就是这个

<块引用>

您可以将 NSArray 或 NSDictionary 存储为可转换属性.这将使用 NSCoding 将数组或字典序列化为 NSData 属性(并在访问时适当地反序列化)" - 来源

或者如果您想将其声明为二进制数据,请阅读此简单文章:

I need to save my array to Core Data.

let array = [8, 17.7, 18, 21, 0, 0, 34]

The values inside that array, and the number of values are variable.

1. What do I declare inside my NSManagedObject class?

class PBOStatistics: NSManagedObject, Equatable {
    @NSManaged var date: NSDate
    @NSManaged var average: NSNumber
    @NSManaged var historicAverage: NSNumber
    @NSManaged var total: NSNumber
    @NSManaged var historicTotal: NSNumber
    @NSManaged var ordersCount: NSNumber
    @NSManaged var historicOrdersCount: NSNumber
    @NSManaged var values: [Double]  //is it ok?

    @NSManaged var location: PBOLocation

}

2. What do I declare inside my .xcdatamodel?

3. How do I save this in my Entity? (I use MagicalRecord)

let statistics = (PBOStatistics.MR_createInContext(context) as! PBOStatistics)
statistics.values = [8, 17.7, 18, 21, 0, 0, 34] //is it enough?

解决方案

Ok, I made some research and testing. Using Transformable type, solution is simple:

1. What do I declare inside my NSManagedObject class?

@NSManaged var values: [NSNumber]  //[Double] also works

2. What do I declare inside my .xcdatamodel?

Transformable data type.

3. How do I save this in my Entity?

statistics!.values = [23, 45, 567.8, 123, 0, 0] //just this

"You can store an NSArray or an NSDictionary as a transformable attribute. This will use the NSCoding to serialize the array or dictionary to an NSData attribute (and appropriately deserialize it upon access)" - Source

Or If you want to declare it as Binary Data then read this simple article:

这篇关于如何将数组保存到 CoreData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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