【问题标题】:Objective c - create a variable name at runtime and evaluate its valueObjective c - 在运行时创建一个变量名并评估它的值
【发布时间】:2014-02-09 11:42:10
【问题描述】:

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

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,所以无法正常工作...

【问题讨论】:

    标签: ios objective-c runtime objective-c-runtime


    【解决方案1】:

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

    可运行示例:

    #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);      
        }
    }
    

    【讨论】:

    • 你想要的不可能那样,但这对你的用例 IMO 有好处
    【解决方案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 相当慢,如果在运行时不存在密钥,它会使您的程序崩溃,因此它很脆弱。

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多