gpt4 book ai didi

ios - 类名的 NSString 占位符

转载 作者:行者123 更新时间:2023-11-29 10:40:29 25 4
gpt4 key购买 nike

如何使用占位符作为类名?我有基于传入参数的方法,这些方法按名称引用其他类。在下面的粗略示例中,我需要能够仅根据名称加载三个 ViewController 之一(不是 ViewController 数组,因为这只是一个示例)。

-(void)loadViewController:(int)vcNumberToLoad
{
NSString *vcOne = @"firstViewControllerName";
NSString *vcTwo = @"secondViewControllerName";
NSString *vcThree = @"thirdViewControllerName";

NSArray *vcArray = [NSArray arrayWithObjects:vcOne, vcTwo, vcThree, nil];

NSString *nameOfVCToLoad = [vcArray objectAtIndex:vcNumberToLoad];

UIViewController |VALUE OF nameOfVCToLoad| = [[UIViewController alloc] init]; // What is the code to get the value of nameOfVCToLoad to be used as the instance name of the UIVC class
[self.navigationController pushViewController:|VALUE OF nameOfVCToLoad| animated:NO];

}

例如,如果该方法使用参数“1”运行

NSString *nameOfVCToLoad = [vcArray objectAtIndex:vcNumberToLoad]; //this would = secondViewControllerName

UIViewController secondViewControllerName = [[UIViewController alloc] init];
[self.navigationController pushViewController:secondViewControllerName animated:NO];

其他问题似乎表明 [NSClassFromString:nameOfVCToLoad] 可能符合我的需要,如果是的话如何?

最佳答案

您对对象感到困惑。你在找这个

NSClassFromString(vcOne) 将帮助您进行动态类选择

isKindOfClass 将帮助您识别该类是否为给定类

-(void)loadViewController:(int)vcNumberToLoad
{
NSString *vcOne = @"firstViewControllerName";
NSString *vcTwo = @"secondViewControllerName";
NSString *vcThree = @"thirdViewControllerName";


firstViewControllerName *fvc = nil;
secondViewControllerName *svc = nil;
thirdViewControllerName *tvc = nil;


NSArray *vcArray = [NSArray arrayWithObjects:vcOne, vcTwo, vcThree, nil];

NSString *nameOfVCToLoad = [vcArray objectAtIndex:vcNumberToLoad];


UIViewController *aLoadedViewController = [[NSClassFromString(nameOfVCToLoad) alloc] init];

if ([aLoadedViewController isKindOfClass:[NSClassFromString(vcOne)]]) {

fvc = aLoadedViewController;

}
else if ([aLoadedViewController isKindOfClass:[NSClassFromString(vcTwo)]]) {

svc = aLoadedViewController;

}
else if ([aLoadedViewController isKindOfClass:[NSClassFromString(vcThree)]]) {

tvc = aLoadedViewController;

}

[self.navigationController pushViewController:aLoadedViewController animated:NO];

}

关于ios - 类名的 NSString 占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24778297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com