How to use NSString as a key in Objective-C ++ std :: map

I begin work on the Objective-C ++ project, feeling how two languages ​​are synthesized before I make any heavy design. I am very intrigued by how Automated Reference Counting was integrated with C ++: we get the equivalent of smart pointers for NSObjects that handle persistence / NSObjects properly in STL containers (see David Chisnall's article at http://www.informit.com /articles/article.aspx?p=1745876&seqNum=3 ).

I want to use an STL map as a mapping of types from NSStrings to C ++ values. I can declare the mapping as

 std::map<NSString*, MyType> mapping 

With ARC, this mapping handles memory management correctly. But this does not match the correct semantics of the NSString value, because it uses pointer comparisons instead of -[NSString compare:] .

What is the best way to get an STL map to compare strings instead of comparing pointers?
Should I try to specialize in std::less<NSString*> ?
Should I declare an explicit comparator like std::map<NSString*, MyType, MyCompare> ?
Should I wrap the NSString* keys with a smart pointer that implements operator< ?

+6
source share
2 answers

You need a custom comparison object that calls the NSString comparison function, something like this:

 #include <functional> #include <map> struct CompareNSString: public std::binary_function<NSString*, NSString*, bool> { bool operator()(NSString* lhs, NSString* rhs) const { if (rhs != nil) return (lhs == nil) || ([lhs compare: rhs] == NSOrderedAscending); else return false; } }; std::map<NSString*, MyType, CompareNSString> mapping; 
+9
source

Comparing pointers to unmanaged instances of NSString excellent if they are all NSString literals. iow, this will work in MRC under these conditions, unless, of course, there are duplicate string values, and value is what is being compared.

If not, see Ross's more general answer (+1).

0
source

Source: https://habr.com/ru/post/906496/


All Articles