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.