object_getIvar fails to read the value of BOOL iVar

前端 未结 4 1590
长情又很酷
长情又很酷 2020-12-17 08:06

object_getIvar(id object, Ivar ivar) reads the values of iVArs properly but fails on a BOOL type iVar and crashes. I need the values of all iVars of a class

4条回答
  •  情话喂你
    2020-12-17 09:00

    Accessing ivars directly can be done using ARC. You can access both basic C types (char, short, int, etc.) and Objective-C objects. For example, an unsigned char ivar can be accessed using the following pattern. Replacing the type name with other basic types yields an accessor for that type of ivar.

    unsigned char val;
    
    val = ((unsigned char (*)(id, Ivar))object_getIvar)(object, ivar);
    
    NSLog(@"Looks like I got: %u (or character %c)", val, val);
    

    Behind the scenes, you're employing some shenanigans to fake the compiler into thinking that object_getIvar() is actually a function returning the type you are after. This kind of type cast changes the way the compiler calls and interprets the result of object_getIvar, and is required because the basic C types can be 8 to 64 bits big, and only the compiler knows how they're handled when used as return values, which is defined by the ABI used by the architecture you are compiling for.

    Yes it looks funny, but it's the most portable way to do it, and, well, it just works. :-) Using a straight type cast will not work, nor will ARC allow you to do it.

    If the ivar is an object derived from NSObject, you can use the return value directly, or type cast it to the object you're expecting without issues, ARC or no ARC.

提交回复
热议问题