iOS - NSArray indexOfObject不调用自定义的isEqual

时间:2013-04-10 11:17:58

标签: ios objective-c

我有一个覆盖isEqual方法的人员类:

#import "People.h"

@implementation People
@synthesize name = _name;


-(BOOL)isEqual:(id)object {
    NSLog(@"A.isEqual called");

    if ([object isKindOfClass:[NSString class]]) {
        NSString *name = object;
        return [self.name isEqualToString:name];
    }
    return [super isEqual:object];
}

@end

当我在数组中找到人时,它不会调用isEqual方法:

People* p1 = [People new];
        p1.name = @"A";

        People* p2 = [People new];
        p2.name = @"B";

        NSArray* peopleArray = [NSArray arrayWithObjects:p1, p2, nil];

        NSLog(@"find A %ld", [peopleArray indexOfObject:@"A"]);

        NSLog(@"isEqual A -> %@", [p1 isEqual:@"A"] ? @"Yes" : @"No");

这是输出:

2013-04-10 18:15:47.988 runone[6273:303] find A 9223372036854775807
2013-04-10 18:15:47.988 runone[6273:303] A.isEqual called
2013-04-10 18:15:47.989 runone[6273:303] isEqual A -> Yes

你知道为什么吗?

3 个答案:

答案 0 :(得分:7)

即使Apple的文档says isEqual:被发送到数组中的每个对象,它也会反过来 - 将isEqual:发送到您要搜索的对象。

由于假设[a isEqual:b] == [b isEqual:a],它在大多数情况下不应该有任何区别,但在你的情况下它会产生。

以下是一个例子:

People* p1 = [People new];
p1.name = @"A";

People* p2 = [People new];
p2.name = @"B";

People* p3 = [People new];
p3.name = @"C";

NSArray* peopleArray = [NSArray arrayWithObjects:p1, p2, p3, nil];

NSLog(@"find A %ld", (unsigned long)[peopleArray indexOfObject:p3]);

在People's isEqual方法中:

-(BOOL)isEqual:(id)object
{
    NSLog(@"A.isEqual called %@", [self name]);
    ...
}

输出:

A.isEqual called C
A.isEqual called C
find A 2

答案 1 :(得分:4)

如果a == b,则b == a

或者,就Objective-C而言,如果[a isEqual:b],则 [b isEqual:a] 必须也是

您的-isEqual:违反了该规则。

NSArray如何使用isEqual:方法完全是一个实现细节, isEqual:将用于包含测试

答案 2 :(得分:1)

作为kovpas的回答,我改变了isEqual方法以适应新的想法:

#import "People.h"

@implementation People
@synthesize name = _name, age = _age;


-(BOOL)isEqual:(id)object {
    NSLog(@"A.isEqual called");

    if ([object isKindOfClass:self.class]) {
        People *p = object;
        return [self.name isEqualToString:p.name];
    }
    return [super isEqual:object];
}

@end

然后添加所需的字符串以进行比较

        People* p1 = [People new];
        p1.name = @"A";

        People* p2 = [People new];
        p2.name = @"B";

        NSArray* peopleArray = [NSArray arrayWithObjects:p1, p2, nil];

        People* p3 = [People new];
        p3.name = @"A";

        NSLog(@"find A %ld", [peopleArray indexOfObject:p3]);

它会像魅力一样工作:)

2013-04-11 10:28:55.659 runone[1029:303] A.isEqual called
2013-04-11 10:28:55.659 runone[1029:303] find A 0