Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c NSString到类实例变量_Objective C_Ios_Nsstring_Nsobject - Fatal编程技术网

Objective c NSString到类实例变量

Objective c NSString到类实例变量,objective-c,ios,nsstring,nsobject,Objective C,Ios,Nsstring,Nsobject,我正在寻找一种将NSString转换为类实例变量的方法。对于下面的示例代码,假设过滤器是“colorFilter”。我希望将filternameclassinstancegohere替换为colorFilter - (void)filterSelected:(NSString *)filter { self.filternameclassinstancegohere = ….; } 如果筛选值只能是一小部分常量,只需使用枚举和switch语句: enum Filter { Colo

我正在寻找一种将NSString转换为类实例变量的方法。对于下面的示例代码,假设过滤器是“colorFilter”。我希望将filternameclassinstancegohere替换为colorFilter

- (void)filterSelected:(NSString *)filter
{
    self.filternameclassinstancegohere = ….;
}

如果筛选值只能是一小部分常量,只需使用枚举和switch语句:

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

如果筛选值集很大并且可能经常更改,那么您也可以使用。它更复杂但更灵活。

考虑使用一个带有字符串键的NSMutableDictionary实例变量,而不是40个实例变量。

您可以使用
NSSelectorFromString()创建任意选择器。

这将在上面的示例中调用一个方法
colorFilter


在调用之前,最好先检查
respondsToSelector

虽然对于这个问题有很好的建议解决方案,但我发现我需要的是NSClassFromString方法。下面是一个最终实现:

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

}

该类是否具有特定范围的筛选器,并且您正在使用字符串进行设置?您查看过枚举吗?当前筛选器可以是40个NSString名称中的任意一个。我希望这样做的原因是我必须使用switch语句?i、 你理想的方法是self.ColorFilter=什么?请看我的回答。哦!现在我明白了,再看看你的问题,一切都有道理!做得好!好主意。不幸的是,正如我刚才向jrturton解释的那样。我不想使用switch语句。对于另一种情况,这是一个很好的建议。但在我的情况下,我不能应用它。如果你能用你想做的事情来扩展你的问题,我相信我们可以为你找到一个解决方案:)这是另一种情况下的另一个好建议。但是在我的例子中,它不能被应用。像
[self-setValue:@“SomeValue”forKey:filter]
这样的键/值编码可能会起作用。但这可能会导致安全问题。。。
- (void)filterSelected:(NSString *)filter
{
    //self.filternameclassinstancegohere = ….;
    self.myViewController = [[NSClassFromString(filter) alloc] initWithNibName:filter bundle:nil];

}