在我的应用程序中,我有一个自定义的NSObject,它包含2个可变数组。 我需要将这个自定义的NSOBject保存到核心数据实体中,但我不知道如何实现这一点...
经过一番搜索,我发现,最好的方法是将nsobject转换为nsdata并将其保存在实体的可转换字段中......但我不知道该怎么做。 有人能帮助我吗?
继承人为我的自定义对象编写代码:
MeasureData.h
@interface MeasureData : NSObject{
}
@property (nonatomic, strong) NSMutableArray *questionsData;
@property (nonatomic, strong) NSMutableArray *answersData;
- (id) init;
@end
MeasureData.m
#import "MeasureData.h"
@implementation MeasureData
@synthesize questionsData;
@synthesize answersData;
#pragma mark -
#pragma mark int
- (id)init
{
self = [super init];
// 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 = [[NSBundle mainBundle] pathForResource:
@"questions.list" ofType:@"plist"];
NSMutableArray *questions = [NSMutableArray arrayWithContentsOfFile:path];
/*
[questionsData insertObject:(NSString *)string atIndex:0];
*/
return questions;
}
-(NSMutableArray *)makeAnswersArray
{
// Initalize answers array
NSMutableArray *answers = [NSMutableArray arrayWithCapacity:0];
return answers;
}
-(id)initWithCoder:(NSCoder *)decoder {
if ((self=[super init])) {
questionsData = [decoder decodeObjectForKey:@"questionsData"];
answersData = [decoder decodeObjectForKey:@"answersData"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:questionsData forKey:@"questionsData"];
[encoder encodeObject:questionsData forKey:@"questionsData"];
}
@end
根据第一条评论,我为我的自定义类实现了编码器/编码器功能。并试图存档和编码它(我是ios的新手,所以它可能完全错误) - 但它不起作用......有人能告诉我什么是错的吗?
继承编码(不适用于XD):
NSMutableData *dataToSave = (NSMutableData *)self.measureData;
NSKeyedArchiver *archiverForData = [[NSKeyedArchiver alloc] initForWritingWithMutableData:dataToSave];
[archiverForData encodeObject:dataToSave forKey:@"dataToSave"];
[archiverForData finishEncoding];
//
//theMeasure is the CoreData Entity
theMeasure.result = dataToSave;
答案 0 :(得分:2)
概述:
在我对这个问题的回答中,您可以找到一些有用的链接:NSCoding VS Core data