我有2名经理。一个是另一个的孩子。
管理员1.h
@protocol LoginDelegate <NSObject>
-(id) loginOK: (id) response;
-(id) loginKO: (id) response;
@end
@protocol LogoutDelegate <NSObject>
-(id) logoutOK: (id) response;
-(id) logoutKO: (id) response;
@end
@interface Manager1 : NSObject
- (id) init __attribute__((unavailable("You have to use Manager2 instead.")));
-(id) login;
-(id) logout;
@end
经理1.m
@interface Manager1 ()
@property (nonatomic, weak) id <LoginDelegate> loginDelegate;
@property (nonatomic, weak) id <LogoutDelegate> logoutDelegate;
@end
@implementation Manager1
- (id)initWithDelegate:(id)aDelegate
{
self.logoutDelegate = aDelegate;
self.loginDelegate = aDelegate;
return self;
}
管理器2.h
@protocol OperationDelegate <NSObject>
-(id) operationOK: (id) response;
-(id) operationKO: (id) response;
@end
@interface Manager2 : Manager1
+ (Manager2 *)sharedInstance;
-(id)init __attribute__((unavailable("You have to use initWithDelegate instead.")));
-(id)initWithDelegate:(id)aDelegate;
-(void)doOperation;
@end
经理2
@interface Manager2 ()
@property (nonatomic, weak) id <OperationDelegate> operationDelegate;
@end
@implementation Manager2
- (id)initWithDelegate:(id)aDelegate
{
if (self = [super initWithDelegate : aDelegate])
{
self.operationDelegate = aDelegate;
}
return self;
}
其实,我可以没有任何问题执行我的方法。 (快速示例):
ViewController.m
let manager2 = Manager2(delegate: self)
manager2.login()
manager2.logout()
manager2.doOperation()
我的代表的回应是:
func loginOK(response: id) {
}
func loginKO(response: id) {
}
现在,我想要一个Manager2单例。我在Manager2.m中尝试过:
static Manager2 *sharedManager = nil;
+ (Manager2 *) sharedManager
{
@synchronized(self)
{
if (sharedManager == nil)
sharedManager = [[self alloc] initWithDelegate:self];
}
return sharedManager;
}
ViewController1.m它可以响应。
let manager2 = Manager2(delegate: self)
ViewController2.m什么都不响应。代表无效。
let manager2 = Manager2.sharedIntance()
我怎样才能做到这一点?我必须在sharedInstance中发送我的委托吗?非常感谢你
最佳答案
确切地说,您使用Manager2
初始化了自己的Manager1's initWithDelegate
实例
- (id)initWithDelegate:(id)aDelegate{
if (self = [super initWithDelegate:aDelegate]){
self.operationDelegate = aDelegate;
}
return self;
}
但是
Manager1
并未初始化它,而是应该将其初始化- (id)initWithDelegate:(id)aDelegate{
if (self = [super init]){
self.logoutDelegate = aDelegate;
self.loginDelegate = aDelegate;
}
return self;
}
关于swift - Singleton Manager initWithDelegate,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37183233/