Whats the maximum key length in NSDictionary?
I'm currently working on an app which displays a bunch of files in a table, and you can add and remove them and whatsoever. To prevent duplicates in the table, I'd like to create a NSDictionary using the files full path as keys for another NSDictionary which contains all the file information, but I am a little concerned about the maximum key开发者_开发问答 length of NSDictionary, and also whether this solution would be performance killer or not...
There are no specific limits on the size of the NSString you use as long as it's not so big you fill up all the memory! The dictionary doesn't load in the characters and start looking at them itself so there won't be any internal NSDictionary issues related to that, or performance issues, as all it does is use the isEqual: method and if it returns true, it matches.
Hope that helps.
There is no specific limit. One prerequisite for dictionaries is that the key must conform to the NSCopying
protocol. When you insert a key-value pair into a dictionary, the dictionary makes a copy of the key object to ensure that it does not mutate while inside the dictionary. It uses the key object's hash value to determine where to order it internally. If the object mutated while it was in the dictionary, it would throw the ordering off and the dictionary wouldn't work, so that's why the dictionary makes a copy (although as an optimisation, when immutable objects such as NSString
are asked for a copy, it could simply increase the retain count and return itself, but this is an implementation detail).
Since keys must conform to the NSCopying
protocol, it means you can use a number of objects as keys to a dictionary, including NSArray
, NSData
, etc. Do not worry about performance of using large strings in NSDictionary
collections unless you have discovered that this is actually a bottleneck.
There is no maximum whatsoever, except perhaps the maximum length of NSString, which I think is theoretically unlimited/UIntMax. The NSDictionary interface necessitates indexing via the -hash and -isEqual: methods, implemented by whatever object is being used as a key, to allow keys to be anything, not just NSStrings. NSString of course implements both functions, but that is not the point -- the hash is an int, so basically it is up to NSString to find a way to turn its contents into an integer -- it does not have to (and physically cannot) be unique, just repeatable (returning the same result every time). See here for details on hashing. Basically, this means that every NSString -- any object, really -- can have a hash. Therefore, if you can store it in an NSString, then there is no limit on putting it in an NSDictionary. Also, don't worry about performance/dictionaries of dictionaries are a perfectly valid design and are fast enough to be applicable.
There is no theoretical maximum. Also, I wouldn't worry about performance until you determine that it's really a problem.
精彩评论