Reputation: 7100
I know how to find the class of each object inside an array by using isKindOfClass on an object. In my case, the array would have all the objects of the same class and I am trying to find the class name. The below description would help to understand the question better:
I have 2 custom classes and 2 arrays having objects of those classes:
className: ClassA
Array holding objects of ClassA: NSArray *arrayA = [NSArray arrayWithObjects:a1, a2, a3, nil];
className: ClassB
Array holding objects of ClassB: NSArray *arrayB = [NSArray arrayWithObjects:b1, b2, b3, nil];
My controller ControllerA has a method which accepts NSArray as input.
@implementation ControllerA
- (void)someMthod:(NSArray *)myArrayOfObjects
{
// Print the custom class name whose objects are present inside the array.
}
@end
So when I call this method with arrayA as the input array, it should print ClassA without iterating over all the objects inside the array. When I call it by passing arrayB as the input it should print ClassB without iterating over all the objects inside the array.
All the objects inside the array would be of either ClassA or ClassB. It will not have combination of objects from both the classes like [NSArray arrayWithObjects:a1, a2, b1, b2, nil];
Is there a direct way to achieve what I am looking for instead of iterating over each object of the array and using isKindOfClass on it to find its class?
Upvotes: 1
Views: 2438
Reputation: 9093
The [[myArrayOfObjects firstObject] class]
responses are correct and certainly easy to implement. But personally I would solve it like this:
typedef enum {
ClassType1,
classType2
} MyEnumType;
- (void)someMethod:(NSArray *)myObjects withType:(MyEnumType)objType;
If it's your own code that creates the arrays and passes it to someMethod:
, you could easily change the interface so you can pass along the type of object you're using and not have to inspect any of the array elements.
Upvotes: 0
Reputation: 42588
If you are certain that all the objects in the array are of the type of the first item in the array, then it's not so bad.
NSString *className = NSStringFromClass([[myArrayOfObjects firstObject] class]);
Upvotes: 3
Reputation: 954
No, really the only way to find the class of a given object in a collection is to use isKindOfClass
while iterating over them.
Update: This was under the assumption that you needed to check all the objects individually, however if each array is going to contain the same type of objects, @Jeffery Thomas's answer is what you want.
Upvotes: 0
Reputation: 53112
If by print you mean log, you can use:
NSLog(@"%@", [[array firstObject] class]);
Upvotes: 1