0

Is it possible in obj-c to pass some custom code to method in protocol with out creating new class for this purpose ? I spend some time in Java and things like below are pretty comfortable

interface TestInterface {
    void onTest();
}

class testClass{
    void main {
        TestInterface test = new TestInterface(){
            @Override
            void onTest(){
                // some custom code
            }
        };

        someTestMethod(test);
    }

    private someTestMethod(TestInterface pDelegate){
        if (pDelegate != null){
            pDelegate.onTest();
        }
    }
}

Basically is it possible to init protocol variable and override its method?

Błażej
  • 3,617
  • 7
  • 35
  • 62

1 Answers1

0

Try using a block, like this:

@implementation TestObject

- (void)run {
    [self someTestMethodWithBlock:^{
        // some test code
    }];
}

- (void)someTestMethodWithBlock:(void (^)(void))block {
    if (block != nil) {
        block();
    }
}

@end

You can find lots more information, including tutorials, if you type “objective-c blocks” into your favorite search engine.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848