Move selector to multiple objects in Swift

I am trying to reimplement the class in Swift, but have run into problems. My template should have one object that sends methods to the protocol to several other objects.

I have a protocol that looks like this:

@protocol AnalyticsProvider { @optional - (void)showHomePage; - (void)selectedMenuItem:(NSString *)item; // ... // 100 or so more methods :sigh: // ... @end 

The idea is that I can call showHomePage on a singleton and forward it to several objects, each of which will do its job with this message.

I would configure singleton at startup as follows:

 [AppAnalytics sharedAnalytics] setProviders:@[ myFlurryProvider, myOmnitureProvider] ]; 

where myFlurryProvider and myOmnitureProvider are the actual executors of the AnalyticsProvider protocol. And then, in my opinion, the controllers I would have lines like this:

 [[AppAnalytics sharedAnalytics] showHomePage]; 

This should send homepage analytics events to both Flurry and Adobe Omniture. This works because the AppAnalytics class implements the AnalyticsProvider protocol, but does not actually contain code for any of the methods.

By forwardInvocation: in AppAnalytics , I can forward methods to each ie provider

 - (void)forwardImplementation:(NSInvocation *invocation) { for provider in providers if ([provider respondsToSelector:invocation.selector]) [invocation performWithTarget:provider] } 

Without implementing any of my solitary t AppAnalytics , calls are automatically transferred to forwardImplementation: like NSInvocation , but since AppAnalytics protocol-compatible, I get compiler security at the point of call. win the victory. This is quite important, I do not need to actually implement any methods in AppAnalytics, because there are 100 of them, and I do not want the code to be repeated a lot!

Any ideas on how to implement this in Swift, provided NSInvocation forbidden!

+5
source share
1 answer

I'm not sure which class the forwardImplementation method had and where the list of services came from, but it seems that providing default implementations (which do nothing) for each method in your protocol will lead to type safety, without requiring the methods to actually be implemented in any of the classes matching the protocol.

-2
source

Source: https://habr.com/ru/post/1244905/


All Articles