Reputation: 85
I have a Class with an instance variable of an NSArray
of different objects I know should inherit from the same superclass. My question is how do I access the instance variables and methods from another class (its controller) while ensuring that the contents of the array contains only objects that are a subclass of a certain class? I tried implementing a minimal protocol and refencing the objects in the array as type id
and (id *)
but that won't let me access any instance variables or methods of the classes in the array (and rightly so).
In object file
NSArray* components; // contains subclasses of component
In the controller file
subclassofClassObject* object;
is there a subclassOf function, macro, typedef ... etc or a workaround so I can reference the subclasses of component in a subclass of object from a subclass of controller. i.e something to replace subclassofClass.
Upvotes: 0
Views: 88
Reputation: 53000
I don't quite follow what you're asking, but maybe the following will help:
You can determine if you have an instance of a class, or one of its subclasses using isKindOfClass:
. For example given a class MyBaseClass
, then use a cast:
id elem = [components objectAtIndex:ix];
if ([elem isKindOfClass:[MyBaseClass class]])
{
// elem is an instance of MyBaseClass or one of its subclasses so cast is safe
MyBaseClass *mbc = (MyBaseClass *)elem;
// now can access methods, properties and public instance variables
// of MyBaseClass via mbc without warnings
...
}
Upvotes: 0
Reputation: 6413
I'd suggest to think on your architecture design first. You can try to move your logic inside your subclasses implementation:
@interface BaseClass: NSObject {
}
...
- (void) doMySuperImportantStuff: (id)data;
@end
@implementation BaseClass
...
- (void) doMySuperImportantStuff: (id)data
{
// basic implementation here, or common actions for all subclasses
NSLog(@"BaseClass is here");
}
@end
@interface ClassA: BaseClass
{
NSInteger i;
}
...
@end
@implementation ClassA
...
- (void) doMySuperImportantStuff: (id)data
{
// some specific stuff
NSLog(@"ClassA is here, i=%d", i);
}
@end
@interface ClassB: BaseClass
{
NSString *myString;
}
...
@end
@implementation ClassB
...
- (void) doMySuperImportantStuff: (id)data
{
// another specific stuff
NSLog(@"ClassB is here, myString = %@", myString);
}
@end
// client code example
....
NSArray *list = ...; // list of instances of the subclasses from BaseClass
for(BaseClass *item in list) {
[item doMySuperImportantStuff: userData];
}
Upvotes: 2