Katedral Pillon
Katedral Pillon

Reputation: 14864

How to compare two UIButtons for equality

I have two instances of a UIButton, both obtained from the storyboard: one through IBOutlet UIButton myStar and one as the parameter sender of -(IBAction) buttonClicked:(UIButton *) sender. How do I compare myStar and sender without getting false negatives? Although I dragged and dropped from the storyboard, I believe they are two different instances with two different ids.

I can't simply compare the titles or image names because I have multiple such buttons with the same titles and image names.

Upvotes: 0

Views: 1280

Answers (3)

Ethan
Ethan

Reputation: 1567

I think you will find that sender == myStar is true, because they are pointers to the same button, because it sounds like you ctrl+dragged to create an IBOutlet UIButton, then you dragged and dropped to create a IBAction buttonClicked (which passes sender).

sender == myStar always, unless you are calling buttonClicked and passing it other variables programmatically , or if another button from interface builder is linked to that IBAction.

Upvotes: 0

Leeroy Ding
Leeroy Ding

Reputation: 94

sender == myStar indicates that sender is the same instance of myStar, not another instance of UIButton with (maybe accidentally) same value.

In the context, sender == myStar literally means "sender of the message is myStar".

From your description, I believe that you want to make sure the two pointers point to the same object. In this case sender == myStar is the correct way to do it.

Upvotes: 1

Indrajeet
Indrajeet

Reputation: 5666

You can compare two UIButtons by using their tag property, before comparing set tag property for each UIButton. Remember that tag property must be unique.

if (myStar.tag == sender.tag)
{
     code
}

Upvotes: 1

Related Questions