Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@Ciechan Ciechan commented Apr 23, 2014

This actually prints:
1
0
1

@yuriy-tolstoguzov

This comment has been minimized.

Copy link

@yuriy-tolstoguzov yuriy-tolstoguzov commented Apr 23, 2014

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

@JanX2

This comment has been minimized.

Copy link

@JanX2 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
You can’t perform that action at this time.