Does anyone know how to set struct variables using object_setInstanceVariable? It is work fine for reference types:
object_setInstanceVariable(obj, "_variable", ref);
But do not work for structs such as CGPoint. Tried following ways:
1. object_setInstanceVariable(obj, "_variable", point);
2. object_setInstanceVariable(obj, "_variable", &point);
3. object_setInstanceVariable(obj, "_variable", (void **)&point);
I’m not sure I understand what I’m doing (especially for the last step)…
Thanks You in advance!!!
object_setInstanceVariableandobject_getInstanceVariableare really supposed to be used for objects only (though the interface declaration seems to indicate otherwise). You should not use those for builtins.The more appropriate approach is to use
class_getInstanceVariableandivar_getOffset.For example…
That cast up there basically turns the object pointer into a pointer to a byte, so it can be added to the offset (which gives us the pointer to the iVar). We have to go through a
void*first, because ARC does not allow a direct cast touint8_t*.It’s use can be demonstrated thusly…
Now, you have a way to get the pointer of any iVar… just cast the returned
void*appropriately.BTW, I don’t recommend doing this in general, but like any tool, there are uses for the runtime functions.
Oops. Forgot to show setting the value…
EDIT
No. You should not use
object_setInstanceVariableat all. It’s supposed to be used only for instance variables that are objects. Yours is a CGRect, so you should not use that function at all.Use it like the very last example. Maybe this one is a bit more clear (it takes from your example).
Instead of doing something like your question asked:
Do this…
Note, that I defined the
getIvarPointerfunction asstaticwhich has file-local scope. It is not an apple-supplied function – you have to write it. If you are going to use this in multiple places, you need to remove thestaticso the linker can find it.