我们使用coreData时候,会遇到较为复杂的数据类型的存贮,例如,我们要存一个模型,但是一个模型里面有个字典,这时候,我们该如何存贮呢
如图所示,一个对象中含有一个字典
我们实现一个公共的方法,将对象的所有属性都赋值给对应的coreData模型
id makeRemoteModelToCoreDataModel(id remoteModel,Class remoteDataClass,NSManagedObject *coreDataModel) {
int i;
unsigned int propertyCount = 0;
objc_property_t *propertyList = class_copyPropertyList(remoteDataClass, &propertyCount);
NSMutableArray *propertyNameList = [NSMutableArray array];
for ( i=0; i < propertyCount; i++ ) {
objc_property_t *thisProperty = propertyList + i;
const char* propertyName = property_getName(*thisProperty);
NSString *string = [NSString stringWithFormat:@"%s",propertyName];
[propertyNameList addObject:string];
}
if (propertyNameList.count > 0) {
[propertyNameList enumerateObjectsUsingBlock:^(NSString* key, NSUInteger idx, BOOL *stop) {
id obj = [remoteModel valueForKey:key];
if (obj) {
if ([obj isKindOfClass:[NSString class]]) {
[coreDataModel setValue:obj forKey:key];
}else {
NSData *objData = [NSKeyedArchiver archivedDataWithRootObject:obj];
[coreDataModel setValue:objData forKey:key];
}
}
}];
free(propertyList);
return coreDataModel;
}else return nil;
}
存贮数据的时候调用
specialInfoDB = makeRemoteModelToCoreDataModel(specialBO, [specialObjectBO class],specialInfoDB);
在coreData的模型中添加对应的字段,只是数据类型是NSData
如图
读取数据的时候,将coredata的所有字段赋值给我们使用的模型对象
实现的方法
id makeCoreDataModelToRemoteModel(id CoreDataModel,Class remoteDataClass) {
int i;
unsigned int propertyCount = 0;
objc_property_t *propertyList = class_copyPropertyList(remoteDataClass, &propertyCount);
NSMutableArray *propertyNameList = [NSMutableArray array];
for ( i=0; i < propertyCount; i++ ) {
objc_property_t *thisProperty = propertyList + i;
const char* propertyName = property_getName(*thisProperty);
NSString *string = [NSString stringWithFormat:@"%s",propertyName];
[propertyNameList addObject:string];
}
if (propertyNameList.count > 0) {
id dataModal = [[remoteDataClass alloc]init];
[propertyNameList enumerateObjectsUsingBlock:^(NSString* key, NSUInteger idx, BOOL *stop) {
id obj = [CoreDataModel valueForKey:key];
if ([obj isKindOfClass:[NSString class]]) {
[dataModal setValue:obj forKey:key];
}else {
id objFromData = [NSKeyedUnarchiver unarchiveObjectWithData:obj];
[dataModal setValue:objFromData forKey:key];
}
}];
free(propertyList);
return dataModal;
}else return nil;
}
调用
specialObjectBO* specialBO = makeCoreDataModelToRemoteModel(specialInfoDB, [specialObjectBO class]);
这两处重点用到了字典和NSData的相互转化文章来源:https://www.toymoban.com/news/detail-694442.html
NSData *dictData = [NSKeyedArchiver archivedDataWithRootObject:dict];
NSDictionary *subDict = [NSKeyedUnarchiver unarchiveObjectWithData:dictData];
注意点,我们CoreData中的字段是不能直接存贮我们自定义对象类型的,所以,如果我们要存贮的字段如果是一个自定义对象类型,则要将该字段成字段类型,然后转换成Data存贮文章来源地址https://www.toymoban.com/news/detail-694442.html
到了这里,关于iOS 使用coreData存贮页面的模型数据中的字典的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!