views:

7317

answers:

5

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?

+2  A: 

Yes there is:

[object isKindOfClass:[ClassName class]]
Philippe Leybaert
+26  A: 

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]]
mmc
Note that there is also a isMemberOfClass: method that will check for class "exactness." Be careful with it though, as many Apple objects are actually Core Foundation types in disguise. (Eg. an NSString is more often an NSCFString, and isMemberOfClass: will return false for this comparison.)
craig
+4  A: 

You would probably use

  • (BOOL)isKindOfClass:(Class)aClass

This is a function of the 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");

}
Bryan Hare
+1  A: 

This worked better for me:

NSLog(@"=======================================");
        NSLog(@"Is of type: %@", [element class]);
        NSLog(@"Is of type NSString?: %@", ([[element class] isMemberOfClass:[NSString class]])? @"Yes" : @"No");
        NSLog(@"Is a kind of NSString: %@", ([[element classForCoder] isSubclassOfClass:[NSString class]])? @"Yes" : @"No");
codecowboy