Jack Greenhill
Jack Greenhill

Reputation: 10460

Cast object to unknown class

I'm trying to solve a problem that should be simple to solve.

I'm trying to cast an object which is filtered through a NSArray depending on its class, and access a member that is class-specific.

Here's an example:

for (UIView *theView in self.view.subviews) {

        if ([[theView class] isSubclassOfClass:[UIToolbar class]] || [[theView class] isSubclassOfClass:[UINavigationBar class]]) {
                Class theClass = [theView class];
                theClass theObject = (theClass)theView;
                theObject.tintColor = [UIColor colorWithRed:0/255.0f green:128/255.0f blue:255/255.0f alpha:1.0f];
        }

}

That's how I thought I would of done it, but it doesn't compile. I know I could directly cast to UINavigationBar and UIToolbar, but if there was a lot of [[theView class] isSubclassOfClass:[aClass class]], it would make sense to cast it depending on the object's class.

Any help appreciated.

Upvotes: 0

Views: 524

Answers (2)

Caleb
Caleb

Reputation: 125037

if ([theView respondsToSelector:@selector(setTintColor:)]) {
    [theView setTintColor:[UIColor colorWithRed:0/255.0f green:128/255.0f blue:255/255.0f alpha:1.0f]];
}

Upvotes: 2

Anomie
Anomie

Reputation: 94844

Every writable property has a corresponding setter method; unless overridden in the property declaration, this will be named as "set" followed by the property name with the first letter capitalized. And you can send any message to any class, so this will do what you want:

for (UIView *theView in self.view.subviews) {
    if ([[theView class] isSubclassOfClass:[UIToolbar class]] || [[theView class] isSubclassOfClass:[UINavigationBar class]]) {
        [theView setTintColor:[UIColor colorWithRed:0/255.0f green:128/255.0f blue:255/255.0f alpha:1.0f]];
    }
}

To eliminate the warning that UIView may not respond to setTintColor:, cast theView to id.

Upvotes: 1

Related Questions