问题描述
为什么 [MyClass class]
无法在谓词中找到我想要的类的对象, [myObject class] code>工程?请参见下面的代码示例。我想要能够在一个集合中找到类型为MyClass的对象,而不需要有一个类的虚假实例可用。
Why is it that [MyClass class]
fails to find the objects of the class I want in a predicate whereas [myObject class]
works? See code example below. I want to be able to find objects of type MyClass in a set without needing to have a spurious instance of the class available.
MyClass* myObject = [[MyClass alloc] init];
这不起作用...
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"self isMemberOfClass: %@", [MyClass class]];
NSArray* predicateResults = [mySet filteredSetUsingPredicate:predicate].allObjects;
这样工作...
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"self isMemberOfClass: %@", [myObject class]];
NSArray* predicateResults = [mySet filteredSetUsingPredicate:predicate].allObjects;
推荐答案
一个谓词,例如
[NSPredicate predicateWithFormat:@"self isMemberOfClass: %@", [MyClass class]]
实际上可以工作。它返回与(记录的)
actually works. It returns exactly the same predicate as the (documented)
[NSComparisonPredicate
predicateWithLeftExpression:[NSExpression expressionForEvaluatedObject]
rightExpression:[NSExpression expressionForConstantValue:[MyClass class]]
customSelector:@selector(isMemberOfClass:)]
你的情况下的问题可能是 isMemberOfClass:
比较类等于因此这不会匹配作为 MyClass
的子类的成员
的对象。
The problem in your case could be that isMemberOfClass:
compares for class equality, so this would not match objects which are membersof a subclass of MyClass
.
如果 MyClass
是类集群, myObject
是具体子类的实例
。例如:
This could happen if MyClass
is a class cluster and myObject
is an instanceof a concrete subclass. For example:
NSString *myString = [[NSString alloc] initWithUTF8String:"hello world"];
Class c1 = [NSString class]; // NSString
Class c2 = [myString class]; // __NSCFString
BOOL b1 = [myString isMemberOfClass:c1]; // NO
BOOL b2 = [myString isMemberOfClass:c2]; // YES
在这种情况下 [myObject class]
和 [MyClass class]
是不同的,这将解释
为什么一个谓词工作,其他谓词不工作。
In that case [myObject class]
and [MyClass class]
are different, which would explainwhy one predicate works and the other predicate does not work.
以下代码使用 isKindOfClass:
代替并生成预期结果:
The following code uses isKindOfClass:
instead and produces the expected result:
NSArray *array = @[@"123", @456, [NSArray array]];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"self isKindOfClass: %@", [NSNumber class]];
NSArray* predicateResults = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%@", predicateResults);
// Output: ( 456 )
这篇关于NSPredicate isKindOfClass仅适用于[myObject类]而不适用于[MyClass类]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!