将对象转换为未知类

时间:2011-04-02 02:01:34

标签: iphone objective-c class casting member

我正在尝试解决一个应该很容易解决的问题。

我正在尝试转换一个根据其类通过NSArray过滤的对象,并访问一个特定于类的成员。

以下是一个例子:

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];
        }

}

我认为我会这样做,但它不会编译。 我知道我可以直接转换为UINavigationBar和UIToolbar,但是如果有很多[[theView class] isSubclassOfClass:[aClass class]],那么根据对象的类来构建它是有意义的。

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

每个可写属性都有相应的setter方法;除非在属性声明中重写,否则将命名为“set”,后跟属性名称,首字母大写。你可以向任何一个班级发送任何信息,这样你就可以做到:

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]];
    }
}

要消除UIView可能无法响应setTintColor:的警告,请将theView强制转换为id

相关问题