On Sep 19, 2008, at 6:32 AM, Keith Duncan wrote:

you [...] aren't allowed to mutate objects that are in collections

Where is that documented?

It is documented (parenthetically) in the documentation for the -hash method on NSObject.

It is also called out in the Collections programming guide in the NSSet section.

I've been doing this without consideration and nothing's blown up yet.

For a collection which uses the result of -hash to determine the storage location, if you have side effects on hash after storage, you won't be able to correctly locate the object within the collection. Consider:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSMutableString *string = [NSMutableString string];
    NSMutableSet *set = [NSMutableSet set];

    [string appendString:@"Fred"];
    [set addObject: string];

NSLog(@"Before mutation, [set containsObject: string] = %d", [set containsObject: string]);

    [string appendString: @" Flintstone"];

NSLog(@"After mutation, [set containsObject: string] = %d", [set containsObject: string]); NSLog(@"After mutation, [[set allObjects] containsObject: string] = %d", [[set allObjects] containsObject: string]);

    [pool drain];
    return 0;
}

Different frameworks/platforms have subtly different behaviors related to equality/hash value. You can run into this behavior in Java too, depending upon the Object subclass, and its hash/equals behavior. (You won't run into it with StringBuffer because equals() is defined as identity, so a direct port of the above example will not demonstrate the problem.)

Python also takes a somewhat different tact, refusing to store certain mutable objects (raises a TypeError: xxx objects are unhashable) in collections which depend on the hash value.

If this is so fundamental, why haven't I been tripped up by it?

It is an edge case, but one worth knowing about. You have to be storing mutable objects in a collection whose internal storage position depends on the objects hash code.

Jim

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to