8

How would I be able to rewrite the the following utility class to get all the class string values for a specific type - using the Objective-c runtime functions as shown below?

The ARC documentation specifically states that realloc should be avoided and I also get the following compiler error on this this line:

classList = realloc(classList, sizeof(Class) * numClasses);

"Implicit conversion of a non-Objective-C pointer type 'void *' to '__unsafe_unretained Class *' is disallowed with ARC"

The the below code is a reference to the original article which can be found here.

+ (NSArray *)classStringsForClassesOfType:(Class)filterType {

    int numClasses = 0, newNumClasses = objc_getClassList(NULL, 0);
    Class *classList = NULL;

    while (numClasses < newNumClasses) {
        numClasses = newNumClasses;
        classList = realloc(classList, sizeof(Class) * numClasses);
        newNumClasses = objc_getClassList(classList, numClasses);
    }

    NSMutableArray *classesArray = [NSMutableArray array];

    for (int i = 0; i < numClasses; i++) {
        Class superClass = classList[i];
        do {
            superClass = class_getSuperclass(superClass);
            if (superClass == filterType) {
                [classesArray addObject:NSStringFromClass(classList[i])];
                break;
            }           
        } while (superClass);       
    }

    free(classList);

    return classesArray;
}

Your help will be much appreciated.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
RynoB
  • 323
  • 2
  • 14
  • Do an explicit cast (void *) classList. Also consider not using realloc. What are you trying to accomplish here? – Dustin Jul 11 '12 at 14:18
  • 2
    Do you really need to run the code with ARC, or would it be acceptable for you to run the code in non-ARC mode (`-fno-objc-arc` flag in de target build settings for the classes where you want to disable ARC). See: http://stackoverflow.com/questions/6646052/how-can-i-disable-arc-for-a-single-file-in-a-project – Wolfgang Schreurs Jul 11 '12 at 14:22
  • @WolfgangSchreurs Thanks, I totally forgot about the linker flag option. – RynoB Jul 17 '12 at 11:32

1 Answers1

16

ARC forces you to be more explicit with you memory management. In this case, you just need to explicitly cast the output of realloc:

classList = (Class *)realloc(classList, sizeof(Class) * numClasses);
joerick
  • 16,078
  • 4
  • 53
  • 57