C, how do I test the object type?

I need to test whether the object is of type NSString or UIImageView . How can I accomplish this? Is there some type of "isoftype" method?


If your object is myObject , and you want to test to see if it is an NSString , the code would be:

[myObject isKindOfClass:[NSString class]]

Likewise, if you wanted to test myObject for a UIImageView :

[myObject isKindOfClass:[UIImageView class]]

You would probably use

- (BOOL)isKindOfClass:(Class)aClass

This is a method of NSObject .

For more info check the NSObject documentation.

This is how you use this.

BOOL test = [self isKindOfClass:[SomeClass class]];

You might also try doing somthing like this

for(id element in myArray)
{
    NSLog(@"=======================================");
    NSLog(@"Is of type: %@", [element className]);
    NSLog(@"Is of type NSString?: %@", ([[element className] isMemberOfClass:[NSString class]])? @"Yes" : @"No");
    NSLog(@"Is a kind of NSString: %@", ([[element classForCoder] isSubclassOfClass:[NSString class]])? @"Yes" : @"No");    
}

When you want to differ between a superClass and the inheritedClass you can use:

if([myTestClass class] == [myInheritedClass class]){
   NSLog(@"I'm the inheritedClass);
} 
if([myTestClass class] == [mySuperClass class]){
   NSLog(@"I'm the superClass);
} 

Using - (BOOL)isKindOfClass:(Class)aClass in this case would result in TRUE both times because the inheritedClass is also a kind of the superClass.

链接地址: http://www.djcxy.com/p/64818.html

上一篇: 学习WPF和MVVM

下一篇: C,我如何测试对象类型?