【问题标题】:CoreData getting attribute type - how to determine if it is a primitiveCoreData获取属性类型 - 如何确定它是否是原始的
【发布时间】:2013-11-06 14:55:49
【问题描述】:

我正在尝试获取实体的所有属性,然后确定它们的类型 - 我知道我可以在这一行做一些事情:

if(![[thisAttribute attributeValueClassName] isKindOfClass:[NSString class]]) {

但是如何检查 BOOL、浮点数或整数?

到目前为止,这是我的代码:

//get the attributes for this entity - we need to parse the dictionary of data we want to store and convert its contents from NSStrings to whatever type the entity requires
    NSEntityDescription* entity = [NSEntityDescription entityForName:strEntityName inManagedObjectContext:myMOC];
    NSDictionary* dictAttributes = [entity attributesByName];

    for(NSString* strThisKey in dictAttributes) {

        NSAttributeDescription* thisAttribute = [dictAttributes objectForKey:strThisKey];
        NSString* strAttributeType = [thisAttribute attributeValueClassName];

        //look for a match in the data keys (the dict we passed) with the entity keys
        for(NSString* strDataKey in dictDataToStore) {

            //found
            if ([strDataKey isEqualToString:strThisKey]) {

                if(![strAttributeType isEqualToString:@"NSString"]) {

                    //check for whatever else (@"NSDate", @"NSNumber", etc.)
                }
            }
        }

    }

好的,我误解了 NSAttributeDescription 返回给我的内容,我编辑了代码并基本上回答了我的问题。希望这可以帮助其他人。

【问题讨论】:

  • 嗯,据我了解,CoreData 不允许您保存任何原语,因此 BOOL、float 和 int,所有这些都由 NSNumber 包装。我不清楚如何从实体中检查原始类型。
  • 不就是检查NSAttributeDescription对象的attributeType属性(返回一个NSAttributeType值)see here吗?
  • 嗨莱昂纳多 - 是的,我看到了,这就是我改变问题的原因。所以我想这是我的问题 - 当你设置一个属性时,你可以选择 BOOLEAN、INTEGER 16、32 等,如果它全部转换为 NSNumber,你怎么知道该属性是什么类型?
  • 嗨,丹,谢谢,就是这样。叫错树。 : D

标签: objective-c core-data nsentitydescription nsattributedescription


【解决方案1】:

您可以使用NSEntityDescriptionNSPropertyDescription API 来确定建模实体的类型。

我会枚举NSAttributeDescriptionNSAttributeType常量

switch (thisAttribute.attributeType) {
  case NSInteger16AttributeType: { /* do something */; } break;
  case NSDecimalAttributeType  : { /* do something */; } break;
  case NSStringAttributeType   : { /* do something */; } break;
  case NSBooleanAttributeType  : { /* do something */; } break;
  // etc
  default: break;
}

【讨论】:

  • 谢谢,这就是我最终所做的,但您以答案的形式发帖赢得了胜利! : D
  • 我是在你在 cmets 讨论时写的。不过,您必须勾选复选标记。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 2020-01-01
  • 2012-09-03
  • 1970-01-01
相关资源
最近更新 更多