How do I get the Objective-C class of an ivar?

前端 未结 3 1835
你的背包
你的背包 2020-12-21 01:04

I have a bunch of simple NSManagedObjects I create in a unit test. They just have a single name attribute of type NSString *. I always

相关标签:
3条回答
  • 2020-12-21 01:27

    I haven't tried obtaining class information from an ivar, but I know that @property declarations do encode information about the class. For instance, this property declaration:

    @property (copy) NSString *normalString;
    

    results in this attribute string (retrieved using property_getAttributes()) at runtime:

    T@"NSString",C,VnormalString
    

    I've written some open source parsing code for this information.

    Once you have the class name, you can convert it into an actual Class object using NSClassFromString(), and message the result from there.

    Disclaimer: This probably shouldn't be depended upon for production applications, as it is undocumented.

    0 讨论(0)
  • 2020-12-21 01:32

    An id is an id. At runtime, all Objective-C objects have the same type (objc_object). This is tied up in the dynamic nature of ObjC. For example, an object can change classes at runtime, new classes can be created, and the class hierarchy can change. You can ask a specific instance what its type is (since this is stored in objc_object), but a pointer to an object is just a pointer to an object. Even less than that: it's really just a pointer to a C struct that happens to have extra memory allocated at the end (to hold subclass ivars).

    Your macro seems interesting, but you'll probably need to pass the classname as the second parameter rather than autodetecting it.

    0 讨论(0)
  • 2020-12-21 01:43

    Maybe i misunderstand what you are trying to achieve. To get the class of an iVar, can't you use the class method of the iVar?

    like:

    NSString *aString = @"random string";
    NSLog(@"%@",NSStringFromClass([aString class]));
    
    0 讨论(0)
提交回复
热议问题