4

I am looking for a way to convert from NSString to a class instance variable. For sample code below, say filter is "colorFilter". I want filternameclassinstancegohere to be replaced with colorFilter.

- (void)filterSelected:(NSString *)filter
{
    self.filternameclassinstancegohere = ….;
}
user523234
  • 14,323
  • 10
  • 62
  • 102

4 Answers4

5

While there were good suggested solutions given for this question, I discovered what I needed is the NSClassFromString method. Here is a final implementation:

- (void)filterSelected:(NSString *)filter
{
    //self.filternameclassinstancegohere = ….;
    self.myViewController = [[NSClassFromString(filter) alloc] initWithNibName:filter bundle:nil];

}
user523234
  • 14,323
  • 10
  • 62
  • 102
4

Consider using one NSMutableDictionary instance variable with string keys rather than 40 instance variables.

Jakob Egger
  • 11,981
  • 4
  • 38
  • 48
2

You can create an arbitrary selector using NSSelectorFromString():

SEL methodName = NSSelectorFromString(filter);
[self performSelector:methodName];

This will call a method colorFilter in your example above.

Would be wise to check with respondsToSelector before calling, too.

jrturton
  • 118,105
  • 32
  • 252
  • 268
1

If the filter value can only be a small, constant number of things, just use an enumeration and a switch statement:

enum Filter
{
  ColorFilter,
  FooFilter,
  BarFilter
};

- (void)filterSelected:(Filter)filter
{
  switch(filter)
  {
  case ColorFilter:
    self.colorFilter = ...;
    break;
  case FooFilter:
    self.fooFilter = ...;
    break;
  case BarFilter:
    self.barFilter = ...;
    break;
  }
}

If the set of filter values is large and could change frequently, then you could also use Key-Value Coding. It's more complicated but more flexible.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589