我们使用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的相互转化
NSData *dictData = [NSKeyedArchiver archivedDataWithRootObject:dict];NSDictionary *subDict = [NSKeyedUnarchiver unarchiveObjectWithData:dictData];
注意点,我们CoreData中的字段是不能直接存贮我们自定义对象类型的,所以,如果我们要存贮的字段如果是一个自定义对象类型,则要将该字段成字段类型,然后转换成Data存贮