如何使用魔法记录将两个 NSMutableArray 中的数据保存到单个实体中

How to save data in two NSMutableArray into a single entity using magical record

我正在通过调用 API 从网络中获取 codedesc。然后将其加载到 tableView 并基于多项选择,我将所选值保存到两个数组中,即 selectedCodeselectedCodeDesc。我的实体是:



所以我想 [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error){ 但不知道怎么做。我知道这么多:

- (IBAction)confirmPressed:(id)sender {
    NSLog(@"Selected Are: %@ - %@",selectedDX,selectedDesc);
    for (NSString *code in selectedDX) {
        if (!_dxToAddEdit) {
            self.dxToAddEdit = [MainCode MR_createEntity];
        }

        [self.dxToAddEdit setCode:code];
        [self.dxToAddEdit setCodeDescription:@""]; //what to give here
        [self.dxToAddEdit setSuperBill:_forSuperBill];
    }
    //after this I'm calling the saveToPersistent

那么在 setCodeDescription 中给出什么?

如果我理解正确并根据您的描述和代码示例,您可以执行以下操作:

NSManagedObjectContext *defaultContext = [NSManagedObjectContext MR_defaultContext];
// Sorry, I renamed selectedCode to selectedCodes and selectedCodeDesc to selectedCodeDescriptions for readability.
// Not sure whether selectedDX is actually selectedCodes.
for (NSInteger i=0; i<selectedCodes.count; ++i) {
    NSString *code = selectedCodes[i];
    NSString *description = selectedCodeDescriptions[i];
    Diagnoses *newDiagnose = [Diagnoses MR_createEntityInContext:defaultContext];

    newDiagnose.code = code;
    newDiagnose.codeDescription = description;
    newDiagnose.superBill = _forSuperBill;
}

[defaultContext MR_saveToPersistentStoreAndWait];

实际上,我不会将响应保存到两个单独的数组中。因为:

  • 您的代码变得难以阅读
  • 假设模型将发生变化,它将包含 4 个属性而不是两个属性。您将不得不创建额外的数组。

我建议您将响应直接解析为托管对象。当然,您可能不会将它们保存到持久存储中,只是填充您的 table 视图。 我强烈建议您阅读 these tutorials about Core Data。它会让您深入了解如何使用 Magical Record 库。虽然,库简化了很多工作,但最好知道引擎盖下是什么;]