8

I have two NSDictionaries containing NSStrings. To compare this two dictionaries I use isEqualToDictionary: method. The documentation on isEqualToDictionary:says

"Two dictionaries have equal contents if they each hold the same number of entries and, for a given key, the corresponding value objects in each dictionary satisfy the isEqual: test."

So, my strings are compared by isEqual: method.

The question is:
How does isEqual: work for the NSString?

Does it use isEqual: from NSObject? I've read that isEqual from NSObject just compares addresses, using ==. To prove or disprove this idea I wrote a sample:

NSString *str1 = @"sampleString";
NSString *str2 = [NSString stringWithFormat:@"%@", @"sampleString"];
BOOL result = [str1 isEqual:str2];

The result is YES, the addresses of str1 and str2 are different though.
So, either it does not use isEqual: from NSObject (what than?), or NSObject's isEqual: does something more complicated then just checking equality of addresses.

Does anybody know how does it really work?

Anastasia
  • 3,024
  • 1
  • 23
  • 34

3 Answers3

10

NSString overrides isEqual: to properly compare strings, so you're perfectly fine to comparing dictionaries this way.

cobbal
  • 69,903
  • 20
  • 143
  • 156
  • Thanks. Is there a way to make sure of it? Headers and documentation for NSString says nothing. – Anastasia Jul 20 '13 at 00:02
  • I found it, this fact is mentioned in "Objective-c Programming: The Big Nerd Ranch Guide". – Anastasia Jul 20 '13 at 00:13
  • @Anastasia Also, it's very indirectly mentioned in the docs under [`isEqualToString:`](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/isEqualToString:) which says it's the same as `isEqual:` when both are strings, but faster. – cobbal Jul 20 '13 at 05:57
5

isEqualToDictionary compares every object with isEqual.

In my case it doesn't work with NSString object in my dictionary. So i made a very simple workaround. I compare the description of both dictionaries. This works with dictionaries containing NSString and NSNumber and whit all objects containing a description method.

[[myDict1 description] isEqualToString:[myDict2 description]]
Sam
  • 2,707
  • 1
  • 23
  • 32
1

Compare literal descriptions of dictionaries. I'm using it in unit tests.

NSString *a = dictionary.description;
NSString *b = assertation.description;
BOOL test = [a isEqualToString:b];
Geri Borbás
  • 15,810
  • 18
  • 109
  • 172