Question

I have a few keys defined as static vars:

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";

now inside a datasource method where I get the indexpath i would like to create the variable name from a string:

-(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?

I tried

NSString *iconName = [self valueForKey:str];

but it isn't an iVar so not working...

Was it helpful?

Solution

i'd not use static vars but a static dictionary like this:

runnable example:

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

OTHER TIPS

If you make your variables instance variables or properties of an object, then you could use key value coding (KVC) to read and write values to them:

-(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];
  }
}

or

string = [self valueForKey: varName];

As @Daij-Djan points out, though, it's probably better to refactor your code to save your information to a dictionary rather than trying to manipulate your instance variables using string variable names. KVC is fairly slow, and will crash your program if a key doesn't exist at runtime, so it's fragile.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top