【问题标题】:Making Nested JSON in NSDictionary from CoreData从 CoreData 在 NSDictionary 中制作嵌套 JSON
【发布时间】:2016-10-18 17:40:05
【问题描述】:

我不知道标题是否与问题完全一致,但如果您觉得它缺少某些内容,请编辑问题。
我想以特定格式发送参数,例如 JSONAFNeworking in为了将数据保存在服务器上。
我有一个NSArray,其中名为fetchedDX,我将CoreData中的值加载为fetchedDX = [Diagnoses MR_findAllWithPredicate:predicate];,当我在一个地方使用它时,它得到了正确的值,它给了我正确的计数。这是我准备发送的硬编码 NSDictionary:

NSDictionary *superBillData = @{
      @"appointmentID": @"ABC",
      @"patientID": @"ABC",
      @"createdBy": @"ABC",
      @"lastChangedBy": @"ABC",
      @"Diagnoses":@[
            @{
                @"Code":@"hello world",
                @"shortDescription": @"my@you.com"
            },
            @{
                @"Code":@"hello 2",
                @"shortDescription": @"Lorem Ipsum"
                },
            ]};

这里的Diagnoses 键是发送多个对象的键。现在我在fetchedDX 数组中有这些数据作为核心数据给了我,但我不知道如何制作动态NSDictionary,因为这个数组可以有一个或多个计数。因此,基于我必须创建的每个值:

@{
  @"Code":@"hello world",
  @"shortDescription": @"my@you.com"
 }

这是我实体的图片:

任何想法如何实现?

【问题讨论】:

  • 有关系吗?
  • 这个Diagnoses实体有多少个属性?可以分享Diagnoses.h 文件吗?
  • @Adeel 是的,有一个名为SuperBill 的实体与Diagnoses 存在一对多关系。而 superBill 在NSDictionary 中具有高于Diagnoses 的值。
  • 我明白了,我假设CodeshortDescriptionDiagnoses 实体的属性,对吧?我需要确认这一点,因为您将使用这些属性来获得您想要的。
  • 是的,这正是它的本质。 CodeshortDescriptionDiagnoses 的属性。

标签: ios objective-c json core-data


【解决方案1】:

我假设CodeshortDescription 是您的Diagnoses 实体的属性。在Diagnoses.h 中声明一个实例方法- (NSDictionary *)dictionary; 并在您的Diagnoses.m 文件中执行此操作。

- (NSDictionary *)dictionary {

    NSArray *keys = @[@"Code", @"codeDescription"];
    NSDictionary *dict = [self dictionaryWithValuesForKeys:keys];

    return dict;
}

然后你准备参数字典的地方把你的代码改成这个。

NSMutableArray *diagnosesArray = [NSMutableArray array];

    for (Diagnoses *obejct in fetchedDX) {
        [diagnosesArray addObject:[obejct dictionary]];
    }

    NSDictionary *superBillData = @{
                                    @"appointmentID": @"ABC",
                                    @"patientID": @"ABC",
                                    @"createdBy": @"ABC",
                                    @"lastChangedBy": @"ABC",
                                    @"Diagnoses":diagnosesArray};

【讨论】:

  • 这正是我正在寻找的,但请告诉我一件事,哪个类是Diagnoses.hDiagnoses+CoreDataProperties.hDiagnoses+CoreDataClass.h 因为这是我在创建 NSManagedObject 子类时生成的 xcode。
  • NSArray *keys = @[@"Code", @"shortDescription"]; 中还有一个名为superBill 的关系字段。我已经更新了我的问题。
  • Diagnoses+CoreDataClass.h做吧。
  • 如果您只需要 CodeshortDescription 那么就可以了。你不必担心我猜的关系。
  • 是的,您确实不必担心与superBill 的关系。您需要实体的两个属性的值,这就是您需要做的所有事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-30
  • 1970-01-01
  • 2018-06-24
相关资源
最近更新 更多