简体   繁体   中英

Updating an object class reference in a method?

I have an array containing pointers to different objects of UIView subclasses.

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.

I can get the UIView subclass name by going:

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?

The best way is to use the polymorphic property:

You create your UIView class custom and add it your special method:

@interface MyUIView : UIView

- (void)specialMethod;

@end

Then your subviews extend MyUIView instead of UIView :

@interface MyViewA : MyUIView

@end

You override the specialMethod in each sub class:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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