简体   繁体   English

更新方法中的对象类引用?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM