본문 바로가기
iOS/Objective-C

isEqual vs. ==

by 패쓰킴 2021. 11. 11.
728x90

 

NSArray, NSDictionary, NSString과 같은 컨테이너 클래스들은 동일성을 비교할 때 조금 다르다.

NSString * str1 = @"안녕";
NSString * str2 = @"안녕";

if (str1 == str2) {
  // retrun YES
}

if (str1 isEqual:str2) {
  // retrun YES
}


같은 "안녕"을 참조하고 있기 때문에 모두 return YES이다.

(== 와 isEqual이 같은 결과를 리턴하는 이유 : https://ggool.tistory.com/72)

 

그러나

 

NSString * str1 = @"안녕";
NSString * str2 = [NSString stringWithFormat:@"%@",@"안녕"];

if (str1 == str2) {
  // retrun NO
}

if (str1 isEqual:str2) {
  // retrun YES
}


즉, `==` 의 경우 Object의 메모리 주소(포인터)를 비교하고, `isEqual` 은 Object 자체를 비교한다.

 

 

예제처럼 NSString을 비교할 때에는 isEqual 보다 isEqualToString 을 사용하는 편이 더 빠르다. isEqual 은 비교할 대상의 클래스를 모르기 때문.

 

 

참고>>

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=horajjan&logNo=220553010289

https://rhammer.tistory.com/101

https://stackoverflow.com/questions/14036604/objective-c-nsobject-isequal-vs-comparison

https://stackoverflow.com/questions/5054730/comparing-objects-in-obj-c

 

728x90

'iOS > Objective-C' 카테고리의 다른 글

cornerRadius 원하는 부분에만 적용  (0) 2021.12.15
Push Notification  (0) 2021.12.06
_myView vs. self.myView  (0) 2021.11.17
arrow notation (`->`)  (0) 2021.11.16
Text 설정  (0) 2021.11.05

댓글