diff --git a/ivar.c b/ivar.c index 83fadc9..558eaa0 100644 --- a/ivar.c +++ b/ivar.c @@ -108,3 +108,36 @@ PRIVATE void objc_compute_ivar_offsets(Class class) abort(); } } + +//////////////////////////////////////////////////////////////////////////////// +// Public API functions +//////////////////////////////////////////////////////////////////////////////// + +void object_setIvar(id object, Ivar ivar, id value) +{ + char *addr = (char*)&object; + addr += ivar_getOffset(ivar); + *(id*)addr = value; +} + +Ivar object_setInstanceVariable(id obj, const char *name, void *value) +{ + Ivar ivar = class_getInstanceVariable(object_getClass(obj), name); + object_setIvar(obj, ivar, value); + return ivar; +} + +id object_getIvar(id object, Ivar ivar) +{ + return *(id*)(((char*)&object) + ivar_getOffset(ivar)); +} + +Ivar object_getInstanceVariable(id obj, const char *name, void **outValue) +{ + Ivar ivar = class_getInstanceVariable(object_getClass(obj), name); + if (NULL != outValue) + { + *outValue = object_getIvar(obj, ivar); + } + return ivar; +} diff --git a/objc/runtime.h b/objc/runtime.h index e317329..de63aa8 100644 --- a/objc/runtime.h +++ b/objc/runtime.h @@ -266,6 +266,30 @@ size_t class_getInstanceSize(Class cls); */ Ivar class_getInstanceVariable(Class cls, const char* name); +/** + * Sets the object value of a specified instance variable. + */ +void object_setIvar(id object, Ivar ivar, id value); +/** + * Sets a named instance variable to the value specified by *value. Note that + * the instance variable must be a pointer-sized quantity. + */ +Ivar object_setInstanceVariable(id obj, const char *name, void *value); + +/** + * Returns the value of the named instance variable. This should not be used + * with instance variables that are not pointers. + */ +id object_getIvar(id object, Ivar ivar); + +/** + * Returns a named instance variable via the final parameter. Note that + * calling object_getIvar() on the value returned from this function is faster. + * + * Note that the instance variable must be a pointer-sized quantity. + */ +Ivar object_getInstanceVariable(id obj, const char *name, void **outValue); + /** * Returns a pointer to the function used to handle the specified message. If * the receiver does not have a method corresponding to this message then this