Alex Lee Alex Lee - 6 months ago 21
iOS Question

How to temporarily define a subclass with overriding method in Objective-C?

I want to define a method in a class A. The method should be over-writable for any i̶n̶s̶t̶a̶n̶c̶e̶ subclass of the class A. The instances of subclasses will be stored in a NSArray. I tried to use the delegate. But it didn't work. I checked a few articles posted online such as How do I create delegates in Objective-C? and But they seem not what I can use to achieve my goal. Could anyone who are familiar with this give me a hint please?

For example,

I create a base class called BaseClass for the UICollectionViewCell and inside the BaseClass there is a ActionMethod. Click different collection cell will result in a different action. So I will define a subclass for each cell that inherited from BaseClass to implement different action. Then how to overwrite the ActionMethod for each subclass?


A delegate would work here. Another option is to use a callback block, e.g.

@interface Cell : NSObject

@property (nonatomic, copy) void(^onAction)();

- (void)actionMethod;


@implementation Cell

- (void)actionMethod {


Used as

Cell *cell1 = [[Cell alloc] init];
cell1.onAction = ^{
    NSLog(@"Action 1");

Cell *cell2 = [[Cell alloc] init];
cell2.onAction = ^{
    NSLog(@"Action 2");

As you can see, you don't need subclasses, you can just add that code to every cell dynamically.