C++ 的等价物STL容器“对”在 Objective-C 中?
我是 Objective-C 的新手,所以请不要对我做出太多评价。我想知道:是否有可以在 Objective-C 中使用的 C++ STL 对容器的等效项?
我想构建一个包含与 NSBool 关联的 NSInteger 的数组。我知道我可以使用一个数组,其中每个条目都是一个具有单个键值的 NSDictionary,但我发现它有点矫枉过正。
有什么想法吗?
谢谢。
I'm new to Objective-C, so please don't judge me too much. I was wondering: Is there an equivalent of the C++ STL pair container I can use in Objective-C?
I want to build an array that contains an NSInteger associated to an NSBool. I know I could use an array with each entry being a NSDictionary with a single key-value but I find it to be a little overkill.
Any ideas?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以编写自己的数据结构对象 - 对于这样一个简单的情况,这将非常简单:
和一个匹配的实现,然后将您的
Pair
对象粘贴到NSArray
问题中自由的。You can write your own data structure object - for such a simple case, it would be pretty easy:
And a matching implementation, then you stick your
Pair
objects into theNSArray
problem free.您可以在 Objective-C++ 中使用 STL。您所需要做的就是将 .m 文件的扩展名更改为 .mm,我还建议您使用
#import
而不是#include
。这样你就可以使用你的 STL 容器了。You can use the STL in Objective-C++. All you need to do is change the extension of your .m file to .mm and I would also advise you use
#import
instead of#include
. That way you can use your pair STL container.使用匿名结构和结构文字,您可能可以执行类似的操作
,然后阅读,
但如果您命名结构,则会更干净一些。
Using anonymous struct and struct literals, you might be able to do something like
and then to read,
It's a bit cleaner if you name your struct though.
NSNumber 上使用关联对象的 Pair 类别怎么样,类似于下面的代码(未经测试,可能需要 iOS4,因为我不确定何时引入关联对象)。
你可以像这样使用它:
并将其取出:
How about a Pair category on NSNumber that uses associated objects, something like the code below (untested, may require iOS4 as I'm not sure when associated objects were introduced).
You would use it like so:
And to get it out:
另一种选择是(ab)使用单条目 NSDictionary 来存储该对 - 因为 NSDictionary 现在可以定义为强制键入“键”和“值”,并且还支持文字作为语法糖。缺点 - 该对只能保存 NSObject(实例引用)而不是原始值。
示例如下所示:
然后在您的代码中:
继续并打印结果:
它看起来非常像您所期望的。
当您尝试从所谓的“对”中提取价值时,回报时间就会到来。您必须实际从 NSDictionary 中挖掘单个条目,而不是像往常一样通过其“Key”,而是假设只有一个条目,如下所示:
最终产生:
我不特别推荐这种替代方案,但它有其优点和好处。
Yet another option, is to (ab)use a single-entry NSDictionary for storing the pair - since NSDictionary can now be defined to force typed "key" and "value" and also supports literals as syntactic sugar. The drawback - the pair can only hold NSObjects (instance references) and not primitive values.
A sample would look like this:
And then in your code:
Go on and print the results:
and it looks very much like what you'd expect.
Payback time comes as you try to extract values from the so-called "Pair". You have to actually dig that single entry from the NSDictionary, not by its "Key" as usual, but assuming there's only one entry, like this:
which finally yields:
I don't especially recommend this alternative, but it has its niceties and benefits.