iOS - 将 UILabel 组存储到 NSMutableArray 中
我在 foreach 循环中动态创建 UILabel
。运行的每个循环都会创建 1-4 个 UILabel。
我想要的是将这些 UILabels 放入 NSMutableArray 中,然后能够轻松检索数据。
我最初的想法是将这些 UILabels 放入 NSDictionary
并使用 [dictGroupLabels setValue:uiLabel1 forKey:@"uiLabel1"]
然后使用 [dictGroupLabels setValue:uiLabel2 forKey :@"uiLabel2"]
等等。然后将这个字典放入我的 NSMutableArray 中以用于每个循环。后来我可以访问像 UILabel *label = [[myArray objectAtIndex:0] valueForKey:@"uiLabel1"]
BUT 这样的值,不幸的是,由于 UILabels 不工作,所以这些值不起作用不符合 NSCopying 协议。
考虑到这一点,您将如何解决这个问题?
I'm creating UILabel
s dynamically in a for each loop. Every loop that is run creates 1-4 UILabels.
What I want is that I put these UILabels into my NSMutableArray and being able later to easy retrieve the data.
My original thought was to put these UILabels into a NSDictionary
and use [dictGroupLabels setValue:uiLabel1 forKey:@"uiLabel1"]
and then [dictGroupLabels setValue:uiLabel2 forKey:@"uiLabel2"]
and so on. And then put this dictionary into my NSMutableArray for each loop. Later on I could access the values like UILabel *label = [[myArray objectAtIndex:0] valueForKey:@"uiLabel1"]
BUT that unfortunately doesn't work since UILabels don't conform to the NSCopying protocol.
So with this in mind how would you solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个问题提供了有关您想要实现的目标的更多信息。由于您知道您在每种情况下尝试创建的可能标签集,因此我强烈建议使用 可变字典而不是数组。
为了说明这一点,给出以下假设的类定义:
您将具有以下假设的类实现:
这基本上是伪代码,不会成功编译。然而,它将作为一个良好的起点。您可能希望将每个标签字典存储在某个有意义的键下,而不是仅使用循环的索引。希望这有帮助。
this question provided more information on what you are trying to accomplish. Since you know for a fact, the possible set of labels you are trying to create in each case, I would highly recommend using mutable dictionaries instead of arrays.
To illustrate, given the following hypothetical class definition:
You would have the following, hypothetical, class implementation:
This is basically pseudo code and will not successfully compile. However it will serve as a good starting point. You probably want to store each label dictionary under some key that makes sense, instead of just using the loop's index. Hope this helps.
它们不需要遵守 NSCopying 即可添加到数组中。听起来你只需要做这样的事情:
They don’t need to adhere to NSCopying to be added to an array. It sounds like you just need to do something like this: