gpt4 book ai didi

ios - objective-c - 在运行时创建一个变量名并计算它的值

转载 作者:行者123 更新时间:2023-11-28 19:04:37 24 4
gpt4 key购买 nike

我有几个定义为静态变量的键:

static NSString icon_0 = @"image_0.png";
static NSString icon_1 = @"some_image_with_a_different_name.png";
static NSString icon_3 = @"picure_of_a_bear.png";

现在在我获取索引路径的数据源方法中,我想从字符串创建变量名称:

-(UICollectionviewCell*)cellForIndexPath:(NSIndexPath *)path
{
NSString *varName = [NSString stringWithFormat:@"icon_%d",path.row];
// here I need the static NSString which corresponds to the var name created
// i.e
NSString imageName;
if (indexPath.row == 0)
{
imageName = @"image_0.png";
}

// would be much nicer to do something like

NSString *imageName = [varName evaluate]; // get the content out of it...
}

How can I do this on static variable?

我试过了

NSString *iconName = [self valueForKey:str];

但它不是 iVar,所以无法正常工作...

最佳答案

我不会使用静态变量,而是像这样使用静态字典:

可运行的例子:

#import <Foundation/Foundation.h>

NSDictionary *DDImageName(NSString *varName);
NSDictionary *DDImageName(NSString *varName) {
static NSDictionary *dict = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//TODO
//add all names and the image names here
dict = @{@"icon_0": @"image_0.png",
@"icon_1": @"some_image_with_a_different_name.png",
@"icon_2": @"picure_of_a_bear.png"};
});

return dict[varName];
}

//demo only
int main(int argc, char *argv[]) {
@autoreleasepool {
NSString *varName = @"icon_0";
NSString *imgName = DDImageName(varName);
NSLog(@"imageName for %@ = %@", varName, imgName);
}
}

关于ios - objective-c - 在运行时创建一个变量名并计算它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21658619/

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