Reputation: 21
If I have objects from the following 3 classes in a NSArray, what's the best way to assign the array elements to the appropriate object?
@interface Simple : NSObject
@interface Intermediate : Simple
@interface Advanced : Simple
I'd like to loop through the NSArray and if the 2nd element of the array is Intermediate and the 5th element is Advanced, I want to assign them to variables of Intermediate and Advanced respectively. This lets me call methods in the derived class that are not defined in the base class.
Let me know if there is a better to go about this than having an NSArray contain different objects (I'm still interested in knowing the answer to the original question)!
Upvotes: 0
Views: 129
Reputation: 108101
You can check the class of the object while looping using either isMemberOfClass:
or isKindOfClass:
(more about the differences here).
That said, if - as I suspect - the three classes share common logic, why don't you just make Simple
, Intermediate
and Advance
subclass of a common ancestor, called - say - Difficulty
, and then use variables of Difficulty
type?
You could then assign any object in the array to the Difficulty
variables regardless of the subclass.
Upvotes: 5
Reputation: 16124
You can easily test what type of class the array entry is via:
id myObject = [myArray objectAtIndex:index];
if ([myObject isMemberOfClass:[Simple class]]) {
//do something
} else if ([myObject isMemberOfClass:[Intermediate class]]) {
//do something
} else if ([myObject isMemberOfClass:[Advanced class]]) {
//do something
}
Upvotes: 0