Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C -- NSObject isEqual, vs. == comparison? [duplicate]

Possible Duplicate:
Comparing objects in Obj-c

What the difference is between these two methods of checking for object equality:

UIButton *btn1 = [[UIButton alloc] init];
UIButton *btn2 = [[UIButton alloc] init];

What is the difference between:

if (btn1 == btn2) {
  // Run some code
}

and

if ([btn1 isEqual:btn2]) {
  // Run some code
}
like image 281
Matt H. Avatar asked Dec 26 '12 06:12

Matt H.


2 Answers

The first way compares pointers, while the second way compares objects.

That is, the first way compares if the pointers have the same value. In this case it is likely that they don't, in the second case the objects will be compared. Since they are initialized the same way they could be equal. (Note, it appears that with the UIButton's implementation of isEqual: the result is always false.)

In most cases using == is not what you want. However, what is appropriate depends on your objective.

like image 78
ThomasW Avatar answered Oct 20 '22 14:10

ThomasW


Prateek's answer and Thomas's edited answer is correct. But I just want to add a common pitfall/confusion when dealing with this type of cases..

Consider this case

 NSString *str1  = [[NSString alloc] initWithString:@"hello"];
 NSString *str2  = [[NSString alloc] initWithString:@"hello"];

Ideally str1 and str2 should be 2 different string objects, str1 and str2 should be pointing to different addresses. But running below code prints str1 == str2

if(str1 == str2){
    NSLog(@"str1 == str2");
}

and below code prints str1 isEqual str2

if([str1 isEqual:str2]){
    NSLog(@"str1 isEqual str2");
}

The reason is, the two identical string literal passed through initWithString will have the same address to start, so they are the same object too (See this). This is the optimization of constant data, which is a feature in iOS (and many other implementation I feel).

But this won't work for other kind of objects/classes. When you create 2 UIButton they will entirely different objects and both btn1 and btn2 (see the question) will points to different address.

like image 37
Krishnabhadra Avatar answered Oct 20 '22 15:10

Krishnabhadra