Note that there are some explanatory texts on larger screens.

plurals
  1. POBest practices for overriding isEqual: and hash
    primarykey
    data
    text
    <p>How do you properly override <code>isEqual:</code> in Objective-C? The "catch" seems to be that if two objects are equal (as determined by the <code>isEqual:</code> method), they must have the same hash value.</p> <p>The <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW25" rel="noreferrer">Introspection</a> section of the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/" rel="noreferrer">Cocoa Fundamentals Guide</a> does have an example on how to override <code>isEqual:</code>, copied as follows, for a class named <code>MyWidget</code>:</p> <pre><code>- (BOOL)isEqual:(id)other { if (other == self) return YES; if (!other || ![other isKindOfClass:[self class]]) return NO; return [self isEqualToWidget:other]; } - (BOOL)isEqualToWidget:(MyWidget *)aWidget { if (self == aWidget) return YES; if (![(id)[self name] isEqual:[aWidget name]]) return NO; if (![[self data] isEqualToData:[aWidget data]]) return NO; return YES; } </code></pre> <p>It checks pointer equality, then class equality, and finally compares the objects using <code>isEqualToWidget:</code>, which only checks the <code>name</code> and <code>data</code> properties. What the example <em>doesn't</em> show is how to override <code>hash</code>.</p> <p>Let's assume there are other properties that do not affect equality, say <code>age</code>. Shouldn't the <code>hash</code> method be overridden such that only <code>name</code> and <code>data</code> affect the hash? And if so, how would you do that? Just add the hashes of <code>name</code> and <code>data</code>? For example:</p> <pre><code>- (NSUInteger)hash { NSUInteger hash = 0; hash += [[self name] hash]; hash += [[self data] hash]; return hash; } </code></pre> <p>Is that sufficient? Is there a better technique? What if you have primitives, like <code>int</code>? Convert them to <code>NSNumber</code> to get their hash? Or structs like <code>NSRect</code>?</p> <p>(<strong>Brain fart</strong>: Originally wrote "bitwise OR" them together with <code>|=</code>. Meant add.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload