Objective-C (iOS): 文字列をクラス名としてインスタンス化する

StringToClassViewController

Objective-C: StringToClassViewController.h

#import <UIKit/UIKit.h>

@interface StringToClassViewController : UIViewController

@end

Objective-C: StringToClassViewController.m

#import "StringToClassViewController.h"

@interface StringToClassViewController ()

@end

@implementation StringToClassViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSArray *definitions = @[
    @{@"className": @"UILabel", @"rect": @"{{0,0},{100,50}}"},
    @{@"className": @"UISwitch", @"rect": @"{{0,50},{100,50}}"},
    @{@"className": @"UISlider", @"rect": @"{{0,100},{100,50}}"}
    ];
    for (int i = 0; i < [definitions count]; i++) {
        NSDictionary *definition = [definitions objectAtIndex:i];
        Class myClass = NSClassFromString([definition objectForKey:@"className"]);
        UIView *view = (UIView *)[[myClass alloc] init];
        view.frame = CGRectFromString([definition objectForKey:@"rect"]);
        [self.view addSubview:view];
    }
}

@end