How to compare objects of your custom NSObject subclass?
Comparison of any two NSObject objects or the objects of NSObject subclass could be very useful, when you are sorting, being unique in collection, or other cases. For example, you need to have your NSObject subclass objects added to or removed from a NSMutableSet, the Set needs to well identify which object is which, so there will be no duplicates. Then, the comparison of objects will be used to help.
How can we do it? Simple.
1st, Overwrite isEqual:(id)object function.
- (BOOL)isEqual:(id)object { if ([object isKindOfClass:[DeviceSensorStruct class]]) { DeviceSensorStruct *obj1 = (DeviceSensorStruct *)object; if (self.deviceID == obj1.deviceID && self.sensorID == obj1.sensorID) { return YES; } else { return NO; } } return NO; }
2nd, Give your object a meaning ful hash value.
- (NSUInteger)hash { return (int)(self.deviceID) * sizeof(unsigned char) + (int)(self.sensorID); }













