pan0rama
pan0rama

Reputation: 21

What's the best way to assign NSArray elements to the appropriate objects?

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

Answers (2)

Gabriele Petronella
Gabriele Petronella

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

Joel
Joel

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

Related Questions