Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

iphone - object_getIvar fails to read the value of BOOL iVar

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.Is there any way to resolve it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...