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

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

问题描述

我需要将数组保存到Core Data。

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

数组中的值和值的数量是可变的。



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

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

@NS管理的变量位置:PBOLocation

}

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





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

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


解决方案

好,我做了一些研究和测试。使用可变性类型,解决方案很简单:



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

  @NSManaged var values:[NSNumber]也可以使用

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



可变形数据类型。 b
$ b

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天全站免登陆