将 NSMutableArray 保存到核心数据 [英] Saving an NSMutableArray to Core Data

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

问题描述

我想将 NSStrings 的 NSMutableArray 添加到我的核心数据模型中的实体之一.问题是这不是 Core Data 支持的类型.

I want to add an NSMutableArray of NSStrings to one of my Entities in my core data model. The problem is that this isn't a supported type in Core Data.

我尝试制作一个可转换的属性,但问题是我看不到将 NSMutableArray 转换为 NSData,然后从 NSData 转换回 NSMutableArray 的方法.有没有人知道如何解决这个问题?

I tried making a tranformable attribute, but the problem is that I see no way of turning a NSMutableArray to NSData, and then going from NSData, back to an NSMutableArray. Does anyone have an idea as to how this issue can be solved?

(我知道我可以存档数组,但我不想这样做,我希望它出现在我的模型中).

(I know I can archive the array, but I don't want to do that, I want it to be present in my model).

推荐答案

您可以在建模对象中有一个二进制数据属性,将数组存档到数据中,然后将其交给对象.

You could have a binary data attribute in your modeled object, archive the array to data, and hand it off to the object.

但我认为更好的方法是建立一对多关系,而不是直接使用数组.

But I think the better way would be to have a to-many relationship, instead of using an array directly.

****这里是如何将数组归档到 NSData 以便它可以在您的托管对象中使用***

**** Here's how to archive the array into NSData so that it can be used in your managed object***

NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:[NSArray arrayWithObjects:@"1",@"2", nil]];

基本上,您拥有的任何符合 NSCoding 协议的类都可以通过这种方式存档.NSArray/NSMutableArray 已经符合它.他们告诉他们所有的对象自己存档,所以他们也必须符合.所有这些对象的成员都必须符合,等等.就像一棵树.

Basically, any class you have which conforms to the NSCoding protocol can be archived in this way. NSArray/NSMutableArray already conform to it. They tell all of their objects to archive themselves, so they must conform too. And all of those objects' members must conform, etc. It's like a tree.

既然你的数组符合,而且它是一个 NSString 数组(它也符合),那么你就是黄金.

Since your array conforms, and it's an array of NSString (which also conforms), then you're golden.

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

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