CoreData getting attribute type - how to determine if it is a primitive

醉酒当歌 提交于 2020-01-05 09:36:19

问题


I'm trying to get all the attributes for an entity and then determine their type - I know I can do something on this line:

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

but how do I check for a BOOL, Float or Integer?

Here's my code so far:

//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.)
                }
            }
        }

    }

OK, I misunderstood what was being returned to me from NSAttributeDescription, I edited the code and essentially answered my question. Hope this helps someone else out.


回答1:


You can use the NSEntityDescription and NSPropertyDescription APIs to determine the kind of a modelled entity.

I would enumerate through NSAttributeDescription's NSAttributeType constants

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;
}


来源:https://stackoverflow.com/questions/19815306/coredata-getting-attribute-type-how-to-determine-if-it-is-a-primitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!