user523234
user523234

Reputation: 14834

NSString to class instance variable

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 = ….;
}

Upvotes: 4

Views: 849

Answers (4)

user523234
user523234

Reputation: 14834

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

}

Upvotes: 5

jrturton
jrturton

Reputation: 119242

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.

Upvotes: 2

Jakob Egger
Jakob Egger

Reputation: 12031

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

Upvotes: 4

Adam Rosenfield
Adam Rosenfield

Reputation: 400204

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.

Upvotes: 1

Related Questions