在Cocoa中,有几个系统类是单例模式,比如UIApplication、NSNotificationCenter等。现在我想找到所有的单例模式类,你有什么建议可以快速找到它们吗?
我正在处理一个巨大的代码库,需要将系统单例对象与自定义单例对象分离开来。
在Cocoa中,有几个系统类是单例模式,比如UIApplication、NSNotificationCenter等。现在我想找到所有的单例模式类,你有什么建议可以快速找到它们吗?
我正在处理一个巨大的代码库,需要将系统单例对象与自定义单例对象分离开来。
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
static BOOL ClassIsSingleton(Class class) {
unsigned int methodCount = 0;
Method *methods = class_copyMethodList(object_getClass(class), &methodCount);
@try {
for (unsigned int i = 0; i < methodCount; i++) {
Method eachMethod = methods[i];
// only consider class methods with no arguments
if (method_getNumberOfArguments(eachMethod) != 2) {
continue;
}
char *returnType = method_copyReturnType(eachMethod);
@try {
// only consider class methods that return objects
if (strcmp(returnType, @encode(id)) != 0) {
continue;
}
}
@finally {
free(returnType);
}
NSString *name = NSStringFromSelector(method_getName(methods[i]));
// look for class methods with telltale prefixes
if ([name hasPrefix:@"shared"]) {
return YES;
} else if ([name hasPrefix:@"standard"]) {
return YES;
} else if ([name hasPrefix:@"default"]) {
return YES;
} else if ([name hasPrefix:@"main"]) {
return YES;
} // feel free to add any additional prefixes here that I may have neglected
}
}
@finally {
free(methods);
}
return NO;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSMutableArray *singletons = [NSMutableArray new];
int classCount = objc_getClassList(NULL, 0);
Class *classes = (Class *)malloc(classCount * sizeof(Class));
@try {
classCount = objc_getClassList(classes, classCount);
for (int i = 0; i < classCount; i++) {
Class eachClass = classes[i];
if (ClassIsSingleton(eachClass)) {
[singletons addObject:NSStringFromClass(eachClass)];
}
}
}
@finally {
free(classes);
}
NSLog(@"Singletons: %@", singletons);
}
return 0;
}
class
属性。 - Rob