Created
December 9, 2014 15:09
-
-
Save period331/91cbeba142c95a90f6c3 to your computer and use it in GitHub Desktop.
== and isEqual Objective-C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
int main(int argc, char * argv[]) | |
{ | |
@autoreleasepool { | |
NSString * str1 = @"hello"; | |
NSString * str2 = [NSString stringWithFormat:@"hello"]; | |
NSLog(@"str1 == str2 ??; %d", (str1 == str2)); // 输出 0 | |
NSLog(@"str1.isEqual ??; %d", [str1 isEqual:str2]); // 输出 1 | |
NSLog(@"str1: %p, str2: %p", str1, str2); // 输出两个不同的地址 | |
NSLog(@"-----------------------------------"); | |
NSString * str3 = [NSString stringWithFormat:@"hello"]; | |
NSString * str4 = [NSString stringWithFormat:@"hello"]; | |
NSLog(@"str3 == str4 ??; %d", (str3 == str4)); // 输出 1 | |
NSLog(@"str3.isEqual ??; %d", [str3 isEqual:str4]); // 输出 1 | |
NSLog(@"str1: %p, str4: %p", str3, str4); // 输出两个相同的地址 | |
} | |
} | |
clang -fobjc-arc -framework Foundation EqualTest.m |
Author
period331
commented
Dec 9, 2014
NSString
已经重写了NSObject
的isEqual
方法,NSString
的isEqual
方法判断两个字符串相等的标准是:
只要两个字符串所包含的字符序列相同就返回真
而 ==
则根据判断的数据的类型变化,如果判断的是两个基本类型的变量,且都是数值型的(并不严格要求数据类型相同),则只要两个变量的值相等,==
就返回1。但是两个指针类型的变量,他们必须指向同一个对象才会返回1。
NSObject
默认提供的isEqual
方法只是比较对象的地址,即NSObject
类的isEqual
方法与==
运算符的比较结果_完全相同
_
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment