gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 06:20:13 32 4
gpt4 key购买 nike

我有一个重写 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

你知道这是为什么吗?

最佳答案

尽管 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 的 isEqual 方法中:

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

输出:

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

关于iOS - NSArray indexOfObject 不调用自定义的 isEqual,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15924368/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com