In Objective-C Determine if a Property is an int, float, double, NSString, NSDate, NSNumber, etc

后端 未结 3 1088
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 21:17

I need to determine an object\'s property (passed by name) type in order to perform deserialization from XML. I have some general pseudo-code (however I am unsure of how to

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 22:05

    If you only care about classes you can use isKindOfClass:, but if you want to deal with scalars you are correct that you need to use property_getAttributes(), it returns a string that encodes the type information. Below is a basic function that demonstrates what you need to do. For examples of encoding strings, look here.

    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([object class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        char *property_name = property_getName(property);
        char *property_type = property_getAttributes(property);
    
        switch(property_type[1]) {
          case 'f' : //float
            break;
          case 's' : //short
            break;
          case '@' : //ObjC object
            //Handle different clases in here
            break;
        }
    }
    

    Obvviously you will need to add all the types and classes you need to handle to this, it uses the normal ObjC @encode types.

提交回复
热议问题