James Raitsev
James Raitsev

Reputation: 96391

How to test equality in Objective-C?

When comparing top views, the first {} fails to execute. == Equality test fails.

In init, i

    [self setCurrentPuzzleView:p1];

And later, i

if ([self currentPuzzleView] == p1) {
    NSLog(@"Removing P1 from SuperView");
    [p1 removeFromSuperview];
} else {
    NSLog(@"Removing P2 from SuperView");
    [p2 removeFromSuperview];
}

Is this now how views should be compared? I thought that == is ok for pointer types

if ([self currentPuzzleView] == p1) {

Relationships between the views are set up via the InterfaceBuilder, where each view (p1, p2 etc) is declared as IBOutlet Puzzle1 *p1.

Upvotes: 3

Views: 1178

Answers (3)

northernman
northernman

Reputation: 1446

Your code looks fine to me.

Perhaps self.currentPuzzleview is being modified elsewhere?

Set a breakpoint in the code and check the values, or print the values in your NSLog() call.

Upvotes: 0

0x8badf00d
0x8badf00d

Reputation: 6401

I would set tag for that view and compare tags.

if(view.tag == 66)
{
 // do something
}
else
{
// else do this
}

Upvotes: 1

James Webster
James Webster

Reputation: 32066

== in Objective-C checks for identity. That is whether two pointers point to the same object.

To test for equality use: [objectA isEqual:objectB]. By default it does the same as == but it can be overridden to have custom equality.

Edit

Having said that and having re-read your question. The two pointers does look as if they are pointing to the same object. Try printing both of the objects you are comparing before you compare them. Also try printing their memory addresses: NSLog(@"Address: %d", &p1); will probably do you.

Upvotes: 5

Related Questions