NSString for class instance variable

I am looking for a way to convert from NSString to a class instance variable. For example code below, for example, the filter "colorFilter". I want to replace filternameclassinstancegohere with colorFilter.

- (void)filterSelected:(NSString *)filter { self.filternameclassinstancegohere = โ€ฆ.; } 
+4
source share
4 answers

Although good recommendations were made for this question, I found that I needed the NSClassFromString method. Here is the final implementation:

 - (void)filterSelected:(NSString *)filter { //self.filternameclassinstancegohere = โ€ฆ.; self.myViewController = [[NSClassFromString(filter) alloc] initWithNibName:filter bundle:nil]; } 
+5
source

Consider using a single instance variable NSMutableDictionary with string keys instead of 40 instance variables.

+4
source

You can create an arbitrary selector using NSSelectorFromString() :

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

In the above example, the colorFilter method will be called.

It would be prudent to check with respondsToSelector before calling.

+2
source

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 can change frequently, you can also use Key-Value Coding . It is more complicated, but more flexible.

+1
source

Source: https://habr.com/ru/post/1383326/


All Articles