0

I'm having some difficulties adding custom equality checks to one of my own objects.

I have a custom Message object which has a unique messageID property which is an NSString, as well as other information about the message.

The objects are being stored in an NSMutableSet, so uniqueness is required in the collection, but I need them to be unique based on the messageID, not the default.

I have added the following code in order to do so.

- (BOOL)isEqual:(id)object
{
    if (![object isKindOfClass:Message.self]) {
        return false;
    }

    if (object == self) {
        return true;
    }

    Message *otherMessage = (Message *)object;

    if ([otherMessage.messageID isEqualToString:self.messageID]) {
        return true;
    }

    return false;
}

- (NSUInteger)hash
{
    return [self.messageID hash];
}

However when I start adding instances of Message objects to a set, the app (sometimes, not always) crashes on one of the following lines:

if ([otherMessage.messageID isEqualToString:self.messageID]) {

OR

return [self.messageID hash];

Basically whenever it tries to access the messageID property.

And the error I get is EXC_BAD_ACCESS.

Any pointers in the right direction would be greatly appreciated!

Matthew Hallatt
  • 1,310
  • 12
  • 24
  • How is `messageID` declared? How is it set? Show some more relevant code. – rmaddy Feb 16 '17 at 17:28
  • Nesting both points of crash within respondsToSelector: is likely to prevent the crash but may have side-effects. Can you verify this? – ystack Feb 16 '17 at 17:33
  • If only I'd remembered to change `assign` to `strong` when I updated the `messageID` property from an `NSInteger` to `NSString`! Thanks rmaddy for the comment that made me realise how stupid the issue was! – Matthew Hallatt Feb 17 '17 at 09:49

0 Answers0