Search code examples
iphoneobjective-ciosnsmutableset

IsEqual Method Sent to Deallocated Instance When Trying to Add Object To MutableOrderedSet


I have an NSMutableOrdered set that holds two types of objects (that I created), Pieces and Others.

Piece and Other both have their isEqual method overridden like so:

Piece:

- (BOOL)isEqual:(Piece *)object
{
    if (([title isEqualToString:[object title]])
        && ([composer isEqualToString:[object composer]])
        && (major == [object major])
        && (tempo == [object tempo])
        && (pieceKey == [object pieceKey])
        && (pieceTime == [object pieceTime]))
        return YES;
    else 
        return NO;
}

Other:

- (BOOL)isEqual:(Other *)object
{
    if (([title isEqualToString:[object title]])
        && ([subTitle isEqualToString:[object subTitle]])
        && ([description isEqualToString:[object description]])
        && (otherTime == [object otherTime]))
        return YES;
    else 
        return NO;
}  

I also override the hash of both classes to create a unique hash for each instance (by getting the int value of the ivars and adding them).

In my app, An Other is removed from the set, then when I try to add a piece to the set, I get this:

-[Other isEqual:]: message sent to deallocated instance 0x80d5680

here is the hash method:

- (NSUInteger)hash
{
    NSUInteger prime = 31;
    NSUInteger result = 1;
    result = prime * (result + [title intValue]);
    result = prime * (result + [composer intValue]);
    result = prime * (result + major);
    result = prime * (result + tempo);
    result = prime * (result + pieceKey);
    result = prime * (result + pieceTime);
    return result;
}

If anybody knows why this is happening, I would really some help.

Thanks,


Solution

  • This is not really an answer, but it will help us to find the problem. Some questions:

    • Are you sure that 0x80d5680 is the instance that was previously removed?
    • How do you remove it from the set?
    • Do you modify the state of your objects after adding them?
    • Are you sure that your hashes are unique (sum of int value of ivars sound sounds suspicious).

    Finally, make sure that your objects obey this rule:

    If two objects are equal, they must have the same hash value. This last point is particularly important if you define isEqual: in a subclass and intend to put instances of that subclass into a collection. Make sure you also define hash in your subclass.

    See NSObject Protocol Reference for more information.