Skip to content

Instantly share code, notes, and snippets.

@Ciechan
Created April 23, 2014 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ciechan/11216080 to your computer and use it in GitHub Desktop.
Save Ciechan/11216080 to your computer and use it in GitHub Desktop.
NSSet trivia
NSMutableString *s = [NSMutableString stringWithString:@"Hello"];
NSSet *set = [NSSet setWithObjects:s, nil];
NSLog(@"%d", [set containsObject:s]);
[s appendString:@"BLA"];
NSLog(@"%d", [set containsObject:s]);
NSLog(@"%d", [set.allObjects containsObject:s]);
@Ciechan
Copy link
Author

Ciechan commented Apr 23, 2014

This actually prints:
1
0
1

@yuriy-tolstoguzov
Copy link

It's took me too long to figure out that it happens because of matching by hash in NSSet.
Sorry for spoilers=)

@JanX2
Copy link

JanX2 commented Apr 24, 2014

Just for reference: the docs clearly state that you must not modify objects in such a way that their hash changes while they are in certain collections. ;)

So don’t do it people!

If a mutable object is added to a collection that uses hash values to determine the object's position in the collection, the value returned by the hash method of the object must not change while the object is in the collection. Therefore, either the hash method must not rely on any of the object's internal state information or you must make sure the object's internal state information does not change while the object is in the collection. Thus, for example, a mutable dictionary can be put in a hash table but you must not change it while it is in there. (Note that it can be difficult to know whether or not a given object is in a collection.)

https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/Protocols/NSObject_Protocol/Reference/NSObject.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment