help with isEquals and hash in iphone - iphone

So i'm overriding isEquals and hash to compare custom objects to be able to remove duplicates from a NSArray. The problem is that i'm missing some values in the list which contains no duplicated items, and it seems that my hash or isEquals implementation is wrong. The custom object is a Course object which has some variables like: id and name I'll put the code here:
- (BOOL)isEqual:(id)object {
if ([object isKindOfClass:[Course self]]) {
return YES;
}
if(self == object){
return YES;
}
else {
return NO;
}
}
- (unsigned)hash {
NSString *idHash = [NSString stringWithFormat: #"%d", self._id];
return [idHash hash];
}
Then, after querying the database i put the values in an array and then in a set which should remove the duplicated items like this:
NSMutableSet *noDuplicates = [[NSMutableSet alloc] initWithArray:tempResults];
Can you see what i'm doing wrong in the isEquals or hash implementation?
Thanks a lot.

Step 1. Decide which instance variables / state are used to determine equality. It's a good idea to make sure properties exist for them (they can be private properties declared in a class extension if you like).
Step 2. Write a hash function based on those instance variables. If all the properties that count are objects, you can just xor their hashes together. You can also use C ints etc directly.
Step 3. Write isEqual: The normal pattern is probably to first test that both objects are in the class or a subclass of the method in which isEqual: is defined and then to test equality for all the properties.
So if a class Person has a name property (type NSString) and a number property (type int) which together define a unique person, hash might be:
-(NSUInteger) hash
{
return [[self name] hash] ^ [self number];
}
isEqual: might be
-(BOOL) isEqual: (id) rhs
{
BOOL ret = NO;
if ([rhs isKindOfClass: [Person class]]) // do not use [self class]
{
ret = [[self name] isEqualToString: [rhs name]] && [self number] == [rhs number];
}
return ret;
}
I don't think it is stated as an explicit requirement in the doc but it is probably assumed that equality is symmetric and transitive i.e.
[a isEqual: b] == [b isEqual: a] for all a and b
[a isEqual: b] && [b isEqual: c]implies [a isEqual: c] for all a, b, c
So you have to be careful if you override isEqual: for subclasses to make sure it works both ways round. This is also why the comment, do not use [self class] above.

Well, your isEqual: implementation really just tests if the two objects are the same class. That's not at all correct. Without knowing the details of your object, I don't know what a good implementation would look like, but it would probably follow the structure
- (BOOL)isEqual:(id)object {
if ([object isMemberOfClass:[self class]]) {
// test equality on all your important properties
// return YES if they all match
}
return NO;
}
Similarly, your hash is based on converting an int into a string and taking its hash. You could also just return the int itself as your hash.

Your code violates the principal of "objects that are equal should have equal hashes." Your hash method generates a hash from self._id and doesn't take that value into consideration when evaluating the equality of the objects.
Concepts in Objective-C Programming has a section on introspection where this topic has examples and coverage. isEqual is meant to answer the question of two objects are equivalent even if they are two distinct instances. So you want to return a BOOL indicating if the object should be considered equivalent. If you don't implement isEqual it will simply compare the pointer for equality which is not what you probably want.
- (BOOL)isEqual:(id)object {
BOOL result = NO;
if ([object isKindOfClass:[self class]]) {
result = [[self firstName] isEqualToString:[object firstName]] &&
[[self lastName] isEqualToString:[object lastName]] &&
[self age] == [object age];
}
return result;
}
From the NSObject Protocol Reference:
Returns an integer that can be used as a table address in a hash table
structure.
If two objects are equal (as determined by the isEqual: method), they
must have the same hash value. This last point is particularly
important if you define hash in a subclass and intend to put instances
of that subclass into a collection.
- (NSUInteger)hash {
NSUInteger result = 1;
NSUInteger prime = 31;
result = prime * result + [_firstName hash];
result = prime * result + [_lastName hash];
result = prime * result + _age;
return result;
}
So what defines two objects as equal is defined by the programmer and their needs. However, whatever methodology of equality is developed, equal objects should have equal hashes.

this is how you implement hash and isEqual (at-least the one which is working for me for purpose of identifying duplicates)
Hash Function
The Apple Doc says that the hash of two objects should be same for those which are considered equal( logically). hence I would implement the hash as below
-(unsigned int)hash
{
return 234;//some random constant
}
isEqual: method implemenation would be something like
-(BOOL)isEqual:(id)otherObject
{
MyClass *thisClassObj = (MyClass*)otherObject;
*// this could be replaced by any condition statement which proves logically that the two object are same even if they are two different instances*
return ([thisClassObj primaryKey] == [self primaryKey]);
}
More reference here : Techniques for implementing -hash on mutable Cocoa objects
Implementing -hash / -isEqual: / -isEqualTo...: for Objective-C collections

Related

Testing object equality, i.e. the same physical address?

I am checking if an object I am getting back from the NSURLConnectionDataDelegate is the same object that I originally created. What I have been doing is:
// TESTING TO SEE IF THE RETURNED OBJECT IS THE SAME ONE I CREATED
if(connection == [self connectionPartial]) {
But was just curious is this is the same as doing:
if([connection isEqual:[self connectionPartial]]) {
It's not the same.
if(connection == [self connectionPartial]) {
This compares the address of the objects, eg. if the pointers point to the same instance.
if([connection isEqual:[self connectionPartial]]) {
This compares the contents of the objects. For instance for two separate NSString instances, this will return YES as long as the string content is the same:
NSString *s1 = #"Something";
NSString *s2 = #"Something";
BOOL sameInstances = (s1 == s2); // will be false, since they are separate objects.
BOOL sameContent = [s1 isEqual:s2]; // will be true, because they both are "Something"
The first snippet compares the values of the pointers themselves, just as if they were any primitive type like an int. If the addresses are the same, the expression will evaluate true.
The second sends the message isEqual: to one of the connection instances. Any class can override isEqual: to define "equality" with another instance. It's entirely possible for a class's implementation of isEqual: to be:
- (BOOL)isEqual: (id)obj
{
return arc4random_uniform(2) ? YES: NO;
}
So, no, for almost all classes they are not equivalent. (NSObject, which has the "default" implementation of isEqual:, uses the objects' hashes, which, again by default, are their addresses.)
It sounds like using the equality operator, ==, is correct in your case.

How to compare strings? (`==` returns wrong value)

I've got myself a piece of the iPhone SDK and been trying to make some simple apps. In this one, i want to compare the first character of self.label.string with the last one of ((UITextField *)sender).text. I decided to name them self.texty and self.input, respectively.
I would expect this if statement returning yes to me under certain circumstances, however I can't seem to get that done.
(in my case, my self.label.string was equal to 'hello!', while my self.input ended in an 'h'.)
self.input = [NSString stringWithFormat:#"%#", [((UITextField *)sender).text substringFromIndex:[((UITextField *)sender).text length]-1]];
self.texty = [NSString stringWithFormat:#"%#", [self.label.string substringToIndex:1]];
if (self.input == self.texty) {
return yes;
} else {
return no;
}
String comparison is not done with ==, but with one of the comparison methods of NSString.
For example:
if ([self.input compare:self.texty] == NSOrderedSame) {
if ([self.input isEqualToString:texty]) {
return yes;
} else {
return no;
}
EDIT:
Or a better version as the commenters noted:
return [self.input isEqualToString:texty];
If you're curious why the == operator doesn't work as expected, it's because you're actually comparing two scalar types (pointers to NSString objects) not the contents of the NSString objects themselves. As a result, it will return false unless the two compared NSStrings are actually the same instance in memory, regardless of the contents.

Compare object properties in different arrays (objective-c)

I have an array of current animal objects that can be viewed by day - for example, monday will return all animals that are available on a monday, etc.
I also have an array of saved animal objects.
How do I ensure that the saved animals don't show up in the current animals list?
Something like, if the currentAnimal.name isEqual to savedAnimal.name?
I need the objects in both arrays so it is important to compare the .name properties, I think?
Override isEqual and hash to do a comparison on the name if that is what you consider to make the objects 'equal'.
- (BOOL)isEqual:(id)other {
if (other == self)
return YES;
if (!other || ![other isKindOfClass:[self class]])
return NO;
return [((MyObject *)other).name isEqualToString:name];
}
and
- (NSUInteger)hash {
return [name hash];
}
You should use isEqual method if you want objects strictly equals or method isKindOfClass.
Look at NSObject reference

How to pass an array to a method and then determine the array's size?

I have this method:
+ (NSData *) createWave: (short[])sampleData {
int i = [sampleData count]; // Warning: Invalid receiver type 'short int *'
}
Inside this method, I'm trying to determine how many elements are in the samples array that was passed in. But I'm getting the warning above (I get the same warning if I change samples to short *).
How can I pass an array like this, and then determine the array's size?
You can't.
Either make sure that the last element in your array is unique and check for that or pass in a size parameter as well i.e.
+ (NSData *) createWave:(short [])samples size:(size_t)count {
int i = count;
}
short[] isn't an object so you can't call methods on it - that's why you're getting a warning (and probably a crash if you run the code!)
You are trying to use a C style array as a parameter and then access it as an Objective-C object. (I am assuming sampleData and samples are supposed to be the same). Use an NSArray of NSNumbers instead because with C style arrays you need to know the length.
+ (NSData *) createWave: (NSArray*)sampleData {
int i = [sampleData count];
}

NSComparisonResult and NSComparator - what are they?

What is NSComparisonResult and NSComparator?
I've seen one of the type definitions, something like that:
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
Is it any different from a function pointer?
Also, I can't even guess what the ^ symbol means.
^ signifies a block type, similar in concept to a function pointer.
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
// ^ ^ ^
// return type of block type name arguments
This means that the type NSComparator is a block that takes in two objects of type id called obj1 and obj2, and returns an NSComparisonResult.
Specifically NSComparator is defined in the Foundation Data Types reference.
And to learn more about C blocks, check out this ADC article Blocks Programming Topics.
Example:
NSComparator compareStuff = ^(id obj1, id obj2) {
return NSOrderedSame;
};
NSComparisonResult compResult = compareStuff(someObject, someOtherObject);
Jacob's answer is good, however to answer the part about "how is this different than a function pointer?":
1) A block is not a function pointer. Blocks are Apple's take on how to make functions first class citizens in C/C++/Objective-C. It's new to iOS 4.0.
2) Why introduce this strange concept? Turns out first class functions are useful in quite a few scenarios, for example managing chunks of work that can be executed in parallel, as in Grand Central Dispatch. Beyond GCD, the theory is important enough that there are entire software systems based around it. Lisp was one of the first.
3) You will see this concept in many other languages, but by different names. For example Microsoft .Net has lambdas and delegates (no relation to Objective-C delegates), while the most generic names are probably anonymous functions or first class functions.
NSComparisonResult comparisionresult;
NSString * alphabet1;
NSString * alphabet2;
// Case 1
alphabet1 = #"a";
alphabet2 = #"A";
comparisionresult = [alphabet1 caseInsensitiveCompare:alphabet2];
if (comparisionresult == NSOrderedSame)
NSLog(#"a and a are same. And the NSComparisionResult Value is %ld \n\n", comparisionresult);
//Result: a and a are same. And the NSComparisionResult Value is 0
// Case 2
alphabet1 = #"a";
alphabet2 = #"B";
comparisionresult = [alphabet1 caseInsensitiveCompare:alphabet2];
if (comparisionresult == NSOrderedAscending)
NSLog(#"a is greater than b. And the NSComparisionResult Value is %ld \n\n", comparisionresult);
//Result: a is greater than b. And the NSComparisionResult Value is -1
// Case 3
alphabet1 = #"B";
alphabet2 = #"a";
comparisionresult = [alphabet1 caseInsensitiveCompare:alphabet2];
if (comparisionresult == NSOrderedDescending)
NSLog(#"b is less than a. And the NSComparisionResult Value is %ld", comparisionresult);
//Result: b is less than a. And the NSComparisionResult Value is 1