[英]Updating an object class reference in a method?
I have an array containing pointers to different objects of UIView
subclasses. 我有一个数组包含指向
UIView
子类的不同对象的指针。
A method is referring to a random one of these objects simply as: 一种方法将这些对象中的随机对象简称为:
- (void)specialMethod(UIView*)target_UIView{
…
}
The question is, I want to refer to the UIView
by its subclass, depending on what it is. 问题是,我想通过它的子类引用
UIView
,具体取决于它是什么。
I can get the UIView
subclass name by going: 我可以通过以下方式获取
UIView
子类名称:
NSString *theClassName = [NSString stringWithFormat:@"%@", [target_UIView class]];
But how can I change the class reference (?) of this object, in the method, from UIView to its actual subclass? 但是如何在方法中将此对象的类引用(?)从UIView更改为其实际的子类?
The best way is to use the polymorphic property: 最好的方法是使用多态属性:
You create your UIView
class custom and add it your special method: 您创建您的
UIView
类自定义并添加您的特殊方法:
@interface MyUIView : UIView
- (void)specialMethod;
@end
Then your subviews extend MyUIView
instead of UIView
: 然后您的子视图扩展
MyUIView
而不是UIView
:
@interface MyViewA : MyUIView
@end
You override the specialMethod
in each sub class: 您覆盖每个子类中的
specialMethod
:
@implementation MyViewA
- (void)specialMethod
{
// Do something
}
@end
and finally, in your method: 最后,在你的方法中:
- (void)specialMethod(MyUIView*)target_UIView{
[target_UIView specialMethod];
…
}
Im not sure about what you are asking, but this method may solve your problem: 我不确定你在问什么,但这种方法可以解决你的问题:
if ([target_UIView isMemberOfClass:[MySubClassView class]])
{
MySubClassView *mySubclassView = (MySubClassView *)target_UIView;
}
You can check if that view belong to that class, and cast it. 您可以检查该视图是否属于该类,并将其强制转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.