In my code, I’m dynamically creating classes, and trying to store them in a NSMutableDictionary:
NSMutableDictionary* classDict = [ [ NSMutableDictionary alloc ] init ];
...start loop
Class customClass = objc_allocateClassPair( [ TestClass class ], className, 0 );
[ classDict setObject:customClass forKey:name ]
...end loop
...add methods to certain classes within the dict
...register classes with objective c
When I run the code, a “EXC_BAD_ACCESS” is thrown when it’s trying to add the Class to the dictionary. Is there a way to get around this? That is, is there a way to add a unregistered Class to a NSMutableDictionary? The alternative solution is to use a std:map data structure instead.
Thanks in advance.
To answer the actual question: adding a
Classobject to a dictionary is simple:And I do so often, without any issue. However, you seem to want to add an unfinished class object. The documentation states:
So maybe your
Classobject is not “ready for use” yet?update after some tests:
you need to call
objc_registerClassPairin order to useClassas an actual object. Callingretainbefore this time will lead to anEXC_BAD_ACCESS.If you want to create classes in a loop, and register them in a later stage, just box the pointers, using:
simply unbox them using
Class customClass = [value pointerValue];. After registering you can of course use theClassobjects as usual.