首页 > 技术文章 > NSString 与 Class/Protocol/SEL 相互转化

nelsen-chen 2018-02-09 22:41 原文

//NSString 与 Class 相互转化

Class NSClassFromString (NSString *aClassName);

NSString * NSStringFromClass (Class aClass);

 

//NSString 与 Protocol 相互转化

NSString * NSStringFromProtocol (Protocol *proto);

Protocol *NSProtocolFromString (NSString *namestr);

 

 

//NSString 与 SEL 相互转化

NSString *NSStringFromSelector (SEL aSelector);

SEL NSSelectorFromString (NSString *aSelectorName);

 

 

我曾经遇到过,在一个页面中可以有9个选择去push 出不同的页面。这样的情况下,如果每个控制器的 push 我都要按照如下代码来写,这岂不是要累死自己, 所以我找了找一个简单的方法。

RegisterViewController *registerVC = [[RegisterViewController alloc] init];
[self.navigationController pushViewController:registerVC animated:YES];

就是利用了NSString 与 Class 的转化:

//将所有控制器类的字符串放入数组 array中
NSArray *arry = [NSArray arrayWithObjects:@"WantToLoanViewController",@"WantToSaleBusinessViewController",@"GetBusinessEverydayViewController",@"LoanGroupViewController",@"PledgeGroupViewController",@"CooperationViewController",@"ReconmmendForMeViewController",@"ActivityAnnouncementsViewController",@"ContactUsViewController", nil];
//取对应类名
NSString *className = [array objectAtIndex:indexPath.row];
Class Representative = NSClassFromString(className);
//创建 Controller 并 push
UIViewController *VC = [[Representative alloc] init];
[self.navigationController pushViewController:VC animated:YES];  



转载自:http://blog.csdn.net/wangyanchang21/article/details/50732572

 

推荐阅读