I want to define a protocol and create a simple, standard way to capture the "default", a common implementation of the specified protocol - singleton style. Cocoa stick to the following pattern:
[NSUserDefaults standardUserDefaults] [NSNotificationCenter defaultCenter]
but in both cases they have @interfaces at the bottom of the object hierarchy. I am afraid how to do this using @protocols. I obviously can create a class that has empty or simple method implementations, but actually I want @protocol at the bottom of the hierarchy. I tried something like:
@protocol ConfigurationManager <NSObject> //... @interface ConfigurationManagerFactory : NSObject + (id<ConfigurationManager>)sharedConfiguration; @end // ... id<ConfigurationManger> config = [ConfigurationManagerFactory sharedConfiguration]; [config ...];
and it works, but I always have to explain how to use it and why I did it this way. Is there a way to conform to Cocoa syntax (calling convention) while using the @protocols value?
Aside, is there a reason why I would not want to use @protocols like this? When implementing @interface, you can still use categories and alternative implementations, etc. - just like instantiating NSString usually leaves you with a class extending NSString.
source share