如何区分 CoreData 中的 Boolean 和 NSNumber

How to tell the difference between a Boolean and an NSNumber in CoreData

我有一些解析代码用于从我们的 Web 服务序列化和反序列化对象,但在序列化布尔值时遇到了一些问题。

序列化看起来像这样:

 - (NSDictionary *)dictionaryRepresentationWithMapping:(NSDictionary *)mappingDictionary
{
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];

    for (id key in[mappingDictionary allKeys])
    {
        id value = [self valueForKey:key];

        if ((value != [NSNull null]) && (![value isKindOfClass:[NSNull class]]) && (value != nil))
        {
            [dictionary setObject:value forKey:mappingDictionary[key]];
        }
    }

    return [NSDictionary dictionaryWithDictionary:dictionary];
}

问题是,当我在我的 NSManagedObject 上调用 valueForKey: 然后将其添加到我的字典时,我最终设置的值就像我在调用时一样:

[dictionary setObject:@1 forKey:mappingDictionary[key]];

而不是:

[dictionary setObject:@YES forKey:mappingDictionary[key]];

这意味着当我将其转换为 JSON 时,在下一阶段,我将向服务器发送 1 而不是 true。

所以我需要的是一种保留事实的方法,即这是一个代表布尔值而不是数字的 NSNumber。我试过询问 class 但我只是返回 NSNumber。有没有一种方法可以自动保留或失败,有没有一种方法可以查询模型以查看属性类型设置为什么?

向服务器发送调用时,您可以这样做: [dict setValue:[NSNumber numberWithBool:YES] forKey:mappingDictionary[key]];; 或者另一种方式,你可以在服务器端建模以将其值保留为布尔值,那时,只需要像这样发送 [dict setValue:YES] forKey:mappingDictionary[key]];

希望能帮到你

每个实体都将其元数据存储在 NSEntityDescriptionNSAttributeDescription 中。您可以通过以下方式从 NSManagedObject 访问它们:

//you can put this inside the for loop
NSAttributeDescription *attributeDescription = self.entity.attributesByName[key];
if(attributeDescription.attributeType == NSBooleanAttributeType) {
  //it is a boolean attribute
}