简体   繁体   English

在foreach循环中消除switch语句

[英]eliminate switch statement in foreach loop

I have question regarding about finding subview using '.tags' in one UIView. 我有一个关于在一个UIView中使用'.tags'查找子视图的问题。

for (UIView *viewObj in [self.view subviews])
{
   // want to find viewObject by its tag.
   // but I heard for-switch or for-case paradigm are bad pattern design by WTF.
   // there are total 9 of tags will be use for finding view object
   switch (viewObj.tag)
   {
         case 0:
         .
         ..
         ...
   }
}

How can I make this to be non-switch or non-if statement? 如何使它成为非切换或非if语句? Should I just add into one array then fetch from there? 我应该只添加到一个数组中然后从那里获取吗? For example, you add views with desired tags and fetch from this array. 例如,您添加带有所需标签的视图并从该数组中获取。

Thank you. 谢谢。

From your comments, it's a very finite set of items that will exist - 9 items. 根据您的评论,这将是一组非常有限的项目-9个项目。 If that is expected to be static, there is nothing really wrong with a switch statement. 如果那是静态的,那么switch语句并没有真正的错误。 Perhaps you can functionally decompose each switch into a separate method. 也许您可以在功能上将每个开关分解为单独的方法。 That said, perhaps the command pattern would be one approach to consider, in addition to your array idea. 话虽如此,也许除了您的阵列想法之外,命令模式也是考虑的一种方法。 For reference: http://en.wikipedia.org/wiki/Command_pattern 供参考: http : //en.wikipedia.org/wiki/Command_pattern

If it is only going to be a fixed number of views and each view has different methods that need to be performed you could access the views directly. 如果仅要使用固定数量的视图,并且每个视图具有需要执行的不同方法,则可以直接访问视图。

UIView* someView = [self.view viewWithTag:0];
//Operations on view 0


UIView* someOtherView = [self.view viewWithTag:1];
//Operations on view 1

//...

One thing you could do is have the UIView s in your subviews be of the same type by having each conform to the same protocol. 您可以做的一件事是,通过使每个subviews都遵循相同的协议,使subviewsUIView具有相同的类型。 Then you could cast each to id<YourProtocol> and call the same method within each UIView . 然后,您可以将每个对象id<YourProtocol>id<YourProtocol>并在每个UIView调用相同的方法。

为了进一步表达Shan的答案,如果可以将它们分解为函数并将它们(函数指针)放入数组中,则可以使其变得更简单,或者可以使用新的“块”语言功能。

There's a new IBOutlet type, IBOutletCollection. 有一个新的IBOutlet类型IBOutletCollection。 You use that for an NSArray, and then in IB you can add views to that outlet - at runtime, they will all be put into the array (unordered). 您可以将其用于NSArray,然后在IB中将视图添加到该插座中-在运行时,它们将全部放入数组中(无序)。

To get out a specific one you want, in viewDidLoad you could map all of the NSArray entries into a dictionary keyed by tag value, then just use "objectForKey" to get them out. 为了找出想要的特定对象,可以在viewDidLoad中将所有NSArray条目映射到由标签值作为键的字典中,然后使用“ objectForKey”将其取出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM