一、介绍
1、==常用来判断两个变量是否相等。
如果两个变量是基本类型的变量,且都是数值型,只要两个变量的值相等,使用==判断就将返回真
int a = 65;
float b = 65.0f;
char ch = 'A';
NSLog(@"%d",a == b);
NSLog(@"%d",a == ch);
2016-06-13 19:54:16.291 isEqualAnd==-test[6947:327865] 1
2016-06-13 19:54:16.292 isEqualAnd==-test[6947:327865] 1
如果两个变量是指针类型,只有两个变量保存的地址相等才会返回为真。
NSString * str1 = @"hello";
NSString * str2 = @"hello";
NSString * str3 = [NSString stringWithFormat:@"hello"];
NSString * str4 = [NSString stringWithFormat:@"hello"];
NSLog(@"str1地址:%p str2地址:%p",str1,str2);
NSLog(@"%d",str1 == str2);
NSLog(@"str3地址:%p str4地址:%p",str3,str4);
NSLog(@"%d",str3 == str4);
NSLog(@"str1地址:%p str3地址:%p",str1,str3);
NSLog(@"%d",str1 == str3);
NSLog(@"str1地址:%p str4地址:%p",str1,str4);
NSLog(@"%d",str1 == str4);
2016-06-13 20:03:23.591 isEqualAnd==-test[7027:333876] str1地址:0x1073ad088 str2地址:0x1073ad088
2016-06-13 20:03:23.591 isEqualAnd==-test[7027:333876] 1
2016-06-13 20:03:23.591 isEqualAnd==-test[7027:333876] str3地址:0xa00006f6c6c65685 str4地址:0xa00006f6c6c65685
2016-06-13 20:03:23.591 isEqualAnd==-test[7027:333876] 1
2016-06-13 20:03:23.591 isEqualAnd==-test[7027:333876] str1地址:0x1073ad088 str3地址:0xa00006f6c6c65685
2016-06-13 20:03:23.591 isEqualAnd==-test[7027:333876] 0
2016-06-13 20:03:23.591 isEqualAnd==-test[7027:333876] str1地址:0x1073ad088 str4地址:0xa00006f6c6c65685
2016-06-13 20:03:23.591 isEqualAnd==-test[7027:333876] 0
2、isEqual是NSObject的方法,只能用来判断两个指针变量是否相等,当两个指针变量保存的地址相等时返回为真。但它跟==的区别是isEqual方法可以重写,来自定义相等的标准。换句话说只要你愿意任何的指针变量都可以通过重写此方法返回相等的结果。
NSString重写了isEqual方法,判断的标准是两个字符串对象所包含的字符是否相等。
NSLog(@"%d",[str1 isEqual:str3]);
返回的结果:
2016-06-13 20:14:47.854 isEqualAnd==-test[7077:340841] 1
isEqual方法重写举例:
- (BOOL)isEqual:(id)object {
// 自己与自己比较永远返回为真
if (object == self) {
return YES;
}
//与空对象比较永远为假
if (object == nil) {
return NO;
}
//不属于同一个类 为假
if (![object isKindOfClass:[MyItem class]]) {
return NO;
}
ClassName *other = (ClassName *)object;
return [other.identifier isEqual:self.identifier];
}
NSString * str1 = @"hello";
NSString * str3 = [NSString stringWithFormat:@"hello"];
NSLog(@"%d",[str1 isEqualToString:str3]);
2016-06-13 20:38:05.036 isEqualAnd==-test[7139:352013] 1