字符串生成Class&Selector&Protocol

NSClassFromString批量化初始化

有时候一个一个类初始化过于麻烦,比如很多的subview

可以用字符串控制类名,然后根据字符串进行初始化等操作

这里属于Runtime的范畴,根本机制是由于OC的消息机制

    NSArray *StrArray = @[@"class0",
                       @"class1",
                       @"class2",
                       @"class3",
                       @"class4"];
    for (int i = 0; i < array.count; ++i) {
        id object = [[NSClassFromString([array objectAtIndex:i]) alloc]init];
        [ClassArray addObject:object];
    }

苹果头文件NSObCRuntime.h中摘抄

FOUNDATION_EXPORT NSString *NSStringFromSelector(SEL aSelector);
FOUNDATION_EXPORT SEL NSSelectorFromString(NSString *aSelectorName);

FOUNDATION_EXPORT NSString *NSStringFromClass(Class aClass);
FOUNDATION_EXPORT Class __nullable NSClassFromString(NSString *aClassName);

FOUNDATION_EXPORT NSString *NSStringFromProtocol(Protocol *proto) NS_AVAILABLE(10_5, 2_0);
FOUNDATION_EXPORT Protocol * __nullable NSProtocolFromString(NSString *namestr)NS_AVAILABLE(10_5, 2_0);

你可能感兴趣的:(字符串生成Class&Selector&Protocol)