Can I use Objective C protocols
the same way I would use Java interfaces
for Dependency Injection or Polymorphism?
It seems like I cannot. Note that in (1) below I have to type the property as the implementation rather than as the protocol. I get a compiler error if I use the protocol as the property
type.
(1) The object to have dependencies injected into:
#import <Foundation/Foundation.h>
#import "FOO_AccountService.h"
#import "FOO_BasicAccountService.h"
@interface FOO_ServiceManager : NSObject
@property (nonatomic, strong) FOO_BasicAccountService <FOO_AccountService> *accountService;
...
@end
(2) The protocol:
#import <Foundation/Foundation.h>
#import "FOO_Service.h"
@protocol FOO_AccountService <FOO_Service>
...
@end
(3) The implementation:
#import <Foundation/Foundation.h>
#import "FOO_BasicService.h"
#import "FOO_AccountService.h"
@interface FOO_BasicAccountService : FOO_BasicService <FOO_AccountService>
...
@end
All you need is:
@property (nonatomic, strong) id<FOO_AccountService> accountService;
Now your property will work with any object type that conforms to the FOO_AccountService
protocol.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.