NSDictionary不区分大小写的objectForKey: [英] NSDictionary case insensitive objectForKey:

查看:130
本文介绍了NSDictionary不区分大小写的objectForKey:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSDictionary具有objectForKey,但是对键区分大小写.像

NSDictionary has objectForKey but it's case-sentive for keys. There is No function available like

- (id)objectForKey:(id)aKey options:(id) options;

您可以在其中的选项中传递"NSCaseInsensitiveSearch"

where in options you can pass "NSCaseInsensitiveSearch"

要从不区分大小写的NSDictionary获取密钥,可以使用下面编写的以下代码.

To get key's from NSDictionary which is case-insesitive one can use the following code written below.

推荐答案

由于以下几个原因而未包含此内容:

This isn't included for a couple of reasons:

  1. NSDictionary使用哈希相等,并且对于几乎所有好的哈希算法而言,源字符串中的任何变化都将导致不同的哈希.

  1. NSDictionary uses hash equality, and for pretty much any good hashing algorithm, any variation in the source string results in a different hash.

更重要的是, NSDictionary键不是字符串.符合NSCopying的任何对象都可以是字典键,并且包含的​​内容比字符串还多.将NSNumber与NSBezierPath进行不区分大小写的比较会是什么样子?

More importantly, NSDictionary keys are not strings. Any object that conforms to NSCopying can be a dictionary key, and that includes a whole lot more than strings. What would a case-insensitive comparison of an NSNumber with an NSBezierPath look like?

这里的许多答案提供的解决方案相当于将字典转换为数组并对其进行迭代.那行得通,如果您只需要一次性使用,那就很好.但是该解决方案有点丑陋,并且具有不良的性能特征.如果这是我急需的(例如,足以创建一个NSDictionary类别),那么我想在数据结构级别上正确解决它.

Many of the answers here offer solutions that amount to transforming the dictionary into an array and iterating over it. That works, and if you just need this as a one-off, that's fine. But that solution is kinda ugly and has bad performance characteristics. If this were something I needed a lot (say, enough to create an NSDictionary category), I would want to solve it properly, at the data structure level.

您想要的是一个包装NSDictionary的类,只允许键的字符串使用,并在给定键时自动将其小写(如果需要双向映射,还可以记住原始键).这将很容易实现,并且设计更加简洁.对于一次性而言,它太重了,但是如果您正在做很多事情,那么我认为值得一试.

What you want is a class that wraps an NSDictionary, only allows strings for keys and automatically lowercases keys as they are given (and possibly also remembers the original key if you need a two-way mapping). This would be fairly simple to implement and is a much cleaner design. It's too heavy for a one-off, but if this is something you're doing a lot, I think it's worth doing cleanly.

这篇关于NSDictionary不区分大小写的objectForKey:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆