ios - 如何在 Core Data 中保存(自定义)NSObject
<p><p>在我的应用程序中,我有一个自定义 NSObject,其中包含 2 个可变数组。
我需要将此自定义 NSOBject 保存到核心数据实体中,但我不知道如何实现这一点...... </p>
<p>经过一番搜索,我发现最好的方法是将 nsobject 转换为 nsdata 并将其保存在实体的可转换字段中......但我不知道该怎么做。
有人可以帮我吗?</p>
<p>这里是我的自定义对象的代码:</p>
<p>MeasureData.h</p>
<pre><code>@interface MeasureData : NSObject{
}
@property (nonatomic, strong) NSMutableArray *questionsData;
@property (nonatomic, strong) NSMutableArray *answersData;
- (id) init;
@end
</code></pre>
<p>测量数据.m</p>
<pre><code>#import "MeasureData.h"
@implementation MeasureData
@synthesize questionsData;
@synthesize answersData;
#pragma mark -
#pragma mark int
- (id)init
{
self = ;
// Initalize questions array (width data from plist)
questionsData = self.makeQuestionsArray;
// NSLog(@"loaded questions array: %@",questionsData); // debug
// Initalize answers array
answersData = self.makeAnswersArray;
// NSLog(@"loaded answers array: %@",answersData); // debug
return self;
}
-(NSMutableArray *)makeQuestionsArray
{
// Initalize questions array (width data from plist)
NSString *path = [ pathForResource:
@"questions.list" ofType:@"plist"];
NSMutableArray *questions = ;
/*
;
*/
return questions;
}
-(NSMutableArray *)makeAnswersArray
{
// Initalize answers array
NSMutableArray *answers = ;
return answers;
}
-(id)initWithCoder:(NSCoder *)decoder {
if ((self=)) {
questionsData = ;
answersData = ;
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder {
;
;
}
@end
</code></pre>
<p>根据第一条评论,我为我的自定义类实现了编码器/编码器功能。并尝试对其进行存档和编码(我是 ios 新手,所以它可能完全错误) - 但它不起作用......有人可以告诉我有什么问题吗?</p>
<p>这里是编码(不工作 XD):</p>
<pre><code>NSMutableData *dataToSave = (NSMutableData *)self.measureData;
NSKeyedArchiver *archiverForData = [ initForWritingWithMutableData:dataToSave];
;
;
//
//theMeasure is the CoreData Entity
theMeasure.result = dataToSave;
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>大纲:</p>
<ul>
<li>创建一个 NSMutableData</li>
<li>使用 initForWritingWithMutableData 在您的数据上创建一个 NSKeyedArchiver</li>
<li>使用 NSCoder 的 encode... 方法序列化您的数组/对象/您需要的任何东西(实现 NSCoding)</li>
<li>使用 BLOB(二进制数据)类型字段创建托管对象</li>
<li>将可变数据中的编码数据写入托管对象的此字段。</li>
</ul>
<p>在我对这个问题的回答中,您可以找到一些有用的链接:<a href="https://stackoverflow.com/questions/9569466/nscoding-vs-core-data/9570385#9570385" rel="noreferrer noopener nofollow">NSCoding VS Core data</a> </p></p>
<p style="font-size: 20px;">关于ios - 如何在 Core Data 中保存(自定义)NSObject,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/9770515/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/9770515/
</a>
</p>
页:
[1]