-
-
Save Ciechan/11216080 to your computer and use it in GitHub Desktop.
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]); |
It's took me too long to figure out that it happens because of matching by hash in NSSet
.
Sorry for spoilers=)
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 thehash
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.)
This actually prints:
1
0
1