ios - EXC_BAD_ACCESS when using object_setIvar -
i attempting add , set ivars on runtime class i've allocated using code below. not have experience objective-c runtime functions that's why trying learn.
if ([object iskindofclass:[nsdictionary class]]) { const char *classname = [aname cstringusingencoding:nsasciistringencoding]; // allocate class using class name, nsobject metaclass, , size of 0 class objectclass = objc_allocateclasspair([nsobject class], classname, 0); // of keys in dictionary use ivars nsdictionary *dictionaryobject = (nsdictionary *)object; nsarray *dictionaryobjectkeys = [dictionaryobject allkeys]; (nsstring *key in dictionaryobjectkeys) { // convert nsstring c string const char *ivarname = [key cstringusingencoding:nsasciistringencoding]; // add ivar class created above using key name if (class_addivar(objectclass, ivarname, sizeof(nsstring*), log2(sizeof(nsstring*)), @encode(nsstring*))) { // newly create ivar class created above using key name ivar ivar = class_getinstancevariable(objectclass, ivarname); // set newly created ivar value of key id value = dictionaryobject[key]; object_setivar(objectclass, ivar, [value copy]); } } objc_registerclasspair(objectclass); }
every time run above code exc_bad_access (code=2, address = 0x10) error on line object_setivar(objectclass, ivar, [value copy]);
. don't understand why getting error. check if ivar added class before attempt set ivar's value, apparently ivar nil. i've tried nslog ivar, same error.
i tried searching on google solution, can't find information on objective-c runtime functions.
i using arc , running app on ios simulator.
you cannot set values instance variables on class. after creating , registering class can create instance of class:
id myinstance = [[objectclass alloc] init];
and set values instance variables on object:
for (nsstring *key in dictionaryobjectkeys) { const char *ivarname = [key cstringusingencoding:nsasciistringencoding]; id value = dictionaryobject[key]; ivar ivar = class_getinstancevariable(objectclass, ivarname); object_setivar(myinstance, ivar, [value copy]); }
Comments
Post a Comment