8

我如何能够重写以下实用程序类以获取特定类型的所有类字符串值 - 使用如下所示的 Objective-c 运行时函数?

ARC 文档明确指出应该避免重新分配,并且我在这一行也收到以下编译器错误:

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

“ARC不允许将非Objective-C指针类型'void *'隐式转换为'__unsafe_unretained Class *'”

下面的代码是对原始文章的引用,可以在此处找到。

+ (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;
}

您的帮助将不胜感激。

4

1 回答 1

16

ARC 迫使您对内存管理更加明确。在这种情况下,您只需要显式地转换 realloc 的输出:

classList = (Class *)realloc(classList, sizeof(Class) * numClasses);
于 2012-07-11T15:13:18.213 回答