пятница, 12 июня 2015 г.

Extending protocol on obj-c

Protocol extension? Well, who stops you from doing that in objective-c?
Maybe, not the way you want, but it works with pretty same logic.

Let’s we have 

@protocol Annoyable <NSObject>

- (void)doMagic;

@end


@interface Routine : NSObject <Annoyable>

@end


@interface SwiftFeatureListening : NSObject <Annoyable>

@end


And you want to add new method to the Annoyable protocol -doMagicTwice which calls doMagic two times.

Just do it using old plain c:

.h:
@protocol Annoyable <NSObject>

- (void)doMagic;

void AnnoyableDoMagicTwice(id<Annoyable> obj);

@end

.m:

void AnnoyableDoMagicTwice(id<Annoyable> obj) {
    [obj doMagic];
    [obj doMagic];
}

Surely, swift way is more easy. But it’s not unique language feature.

The most important the way you think. 
You need to add special method, which implementation is relies on declared protocol methods and does not need any information about concrete classes. 

This is an anonymous method with a protocol-conformed object as argument. Let’s declare and implement method - that’s all!

Update: Got it. You can't override this method in classes. But I'm not sure, that overriding methods implemented in protocol extension is good.