NSString 与 Class 互转

字符串转对象

    Class class = NSClassFromString(self.arr[sender.tag - 100]);

对象转字符串

    VC.navigationItem.title = NSStringFromClass([VC class]);

完整代码

- (void)viewDidLoad {
    [super viewDidLoad];

    self.arr = @[@"ViewController1", @"ViewController2", @"ViewController3", @"ViewController4"];

}


- (IBAction)buttonAction:(UIButton *)sender {
    NSLog(@"--%@--", [NSString stringWithFormat:@"%ld", sender.tag]);

    //字符串 转 对象
    Class class = NSClassFromString(self.arr[sender.tag - 100]);
    UIViewController *VC = [(UIViewController *)[class alloc] init];
    VC.view.backgroundColor = [UIColor whiteColor];
    //对象 转 字符串
    VC.navigationItem.title = NSStringFromClass([VC class]);
    [self.navigationController pushViewController:VC animated:YES];

}

你可能感兴趣的:(ios平台)