我有几个键定义为静态变量:
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所以不能正常工作......
答案 0 :(得分:2)
我不会使用静态变量而是像这样的静态字典:
可运行的例子:
#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);
}
}
答案 1 :(得分:2)
如果您创建变量实例变量或对象的属性,则可以使用键值编码(KVC)来读取和写入值:
-(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)
{
[self setValue = @"image_0.png" forKey: varName];
}
}
或
string = [self valueForKey: varName];
正如@ Daij-Djan指出的那样,重构代码以将信息保存到字典而不是尝试使用字符串变量名来操作实例变量可能更好。 KVC速度相当慢,如果密钥在运行时不存在会导致程序崩溃,因此它很脆弱。