Skip to content

Instantly share code, notes, and snippets.

@period331
Created December 9, 2014 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save period331/91cbeba142c95a90f6c3 to your computer and use it in GitHub Desktop.
Save period331/91cbeba142c95a90f6c3 to your computer and use it in GitHub Desktop.
== and isEqual Objective-C
#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
@period331
Copy link
Author

2014-12-09 23:09:53.933 a.out[2269:370080] str1 == str2 ??; 0
2014-12-09 23:09:53.934 a.out[2269:370080] str1.isEqual ??; 1
2014-12-09 23:09:53.935 a.out[2269:370080] str1: 0x10d744048, str2: 0x6f6c6c656855
2014-12-09 23:09:53.935 a.out[2269:370080] -----------------------------------
2014-12-09 23:09:53.935 a.out[2269:370080] str3 == str4 ??; 1
2014-12-09 23:09:53.935 a.out[2269:370080] str3.isEqual ??; 1
2014-12-09 23:09:53.935 a.out[2269:370080] str1: 0x6f6c6c656855, str4: 0x6f6c6c656855

@period331
Copy link
Author

NSString已经重写了NSObjectisEqual方法,NSStringisEqual方法判断两个字符串相等的标准是:

只要两个字符串所包含的字符序列相同就返回真

==则根据判断的数据的类型变化,如果判断的是两个基本类型的变量,且都是数值型的(并不严格要求数据类型相同),则只要两个变量的值相等,==就返回1。但是两个指针类型的变量,他们必须指向同一个对象才会返回1。

@period331
Copy link
Author

NSObject默认提供的isEqual方法只是比较对象的地址,即NSObject类的isEqual方法与==运算符的比较结果_完全相同_

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment