问题描述
我具有以下对象结构:
动物,狗和猫.如您所料,狗和猫是从动物继承的.
Animal, Dog and Cat. As You expect Dog and Cat are inherited from Animal.
我有一个农场班:
@implementation AnimalFarm
-(Animal*) createAnimal:(AnimalType)type{
switch (type) {
case CAT:
return [Cat new];
case DOG:
return [Dog new];
default:
return [Animal new];
}
}
@end
我试图进行单元测试:
AnimalFarm *farm = [AnimalFarm new];
Animal *dog = [farm createAnimal:DOG];
Animal *cat = [farm createAnimal:CAT];
STAssertTrue([cat isMemberOfClass:[Cat class]],@"cat is not a cat!");
STAssertTrue([dog isMemberOfClass:[Dog class]],@"Dog is not a dog!");
STAssertTrue([cat isKindOfClass:[Animal class]],@"Cat is not an animal!");
STAssertTrue([dog isKindOfClass:[Animal class]],@"Cat is not an animal!");
课程的实现:
@interface Cat : Animal {
}
@end
@implementation Cat
-(NSString*) say{
return @"miau";
}
@end
狗的实施方式与此类似.
Implementation of dog is similar.
但是isKindOfClass或isMemberOfClass都没有按我预期的那样工作....
but neither isKindOfClass or isMemberOfClass worked as I expected....
我想念什么吗?
当我使用IF而不是switch时,一切都很好...但是有什么区别?
When I use IFs instead of switch then everything goes well ... but what is the difference?
createAnimal的实现有效:
Implementation of createAnimal which works:
-(Animal *) createAnimal:(AnimalType)type {
if (type == DOG) {
return [Dog new];
} else if (type == CAT) {
return [Cat new];
} else {
return [Animal new];
}
推荐答案
isMemberOfClass:
仅在实例的类完全相同时返回YES
,但是如果实例的类与实例完全相同,则isKindOfClass:
将返回YES
.相同,或给定类的子类.
isMemberOfClass:
will only return YES
if the instance's class is exactly the same, however isKindOfClass:
will return YES
if the instance's class is the same, or a subclass of the given class.
例如,这将输出No!
:
BOOL result = [[NSMutableArray array] isMemberOfClass:[NSArray class]];
NSLog (@"%@", result? @"Yes!" : @"No!");
但这将输出Yes!
:
BOOL result = [[NSMutableArray array] isKindOfClass:[NSArray class]];
NSLog (@"%@", result? @"Yes!" : @"No!");
这是因为NSMutableArray是NSArray的种类,但它不是NSArray类的成员(否则它将不是NSMutableArray).
This is because an NSMutableArray is a kind of NSArray, but it isn't a member of the NSArray class (otherwise it wouldn't be an NSMutableArray).
在基金会和可可粉中,有许多类集群".您可以在苹果公司的开发人员网站.由于类集群的性质,如果您创建一个NSString
对象,则它可能无法通过isMemberOfClass:[NSString class]
测试.
Throughout Foundation and Cocoa, there are a number of "class clusters". You can read more about this in the documentation on Apple's developer web site. Due to the nature of class clusters, if you create perhaps an NSString
object, it may fail the isMemberOfClass:[NSString class]
test.
如果isKindOfClass:
或isMemberOfClass:
均未返回正确的值,请查看实际对象所在的类
If neither isKindOfClass:
or isMemberOfClass:
is returning the correct value, see what class the actual object is with
NSLog(@"cat class = %@, dog class = %@", [cat className], [dog className]);
如果这些返回的值不符合预期,则说明您的服务器场类存在问题.
If these are returning anything other than what they are supposed to, then there is a problem with your farm class.
这篇关于目标c isKindOfClass误会吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!