isEqual是NSObject的方法,我们常用它来判断两个object是否相等, 而==也常用来来判断两个object是否相等,那么它们有什么区别呢。
看一段代码就明白了:
//MyItem.h
@interface MyItem : NSObject {
@private
NSString *identifier;
}
@property (nonatomic, copy) NSString *identifier;
- (id)initWithIdentifier:(NSString *)anIdentifier;
@end
//MyItem.m
@implementation MyItem
@synthesize identifier;
- (id)initWithIdentifier:(NSString *)anIdentifier {
if (self = [super init]) {
self.identifier = anIdentifier; }
return self;
}
- (BOOL)isEqual:(id)object {
// By default, if two variables point to the same object in memory, it should always be // equal
if (object == self) {
return YES;
}
if (![object isKindOfClass:[MyItem class]]) {
return NO;
}
MyItem *myItem = (MyItem *)object;
return [myItem.identifier isEqual:self.identifier];
}
- (NSUInteger)hash {
return [self.identifier hash];
}
@end
MyItem *item1 = [[MyItem alloc] initWithIdentifier:@"1"];
MyItem *item2= [[MyItem alloc] initWithIdentifier:@"1"];
BOOL ret1 = [item1 isEqual:item2];
BOOL ret2 = (item1 == item2);
看到这儿,请读者猜猜ret1与ret2的值是多少?
上面空了那么多,是时候说答案了。 ret1值为YES, ret2值为NO。
原因就是isEqual比较的是hash返回的值,而==只是简单的内存地址比较,大部份情况==为YES的,isEqual也为YES,如果isEqual为YES的不一定==也为YES。明白了吗?