我有2位经理。一个是另一个孩子。
Manager1.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
Manager1.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;
}
Manager2.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
Manager2.m
@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;
}
实际上,我可以毫无问题地执行我的方法。 (Swift示例):
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中发送我的代理人?非常感谢你
答案 0 :(得分:0)
确切地说,您使用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;
}
答案 1 :(得分:0)
我找到了解决方案:
static Manager2 *sharedInstance = nil;
- (instancetype)init
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = self;
});
return sharedInstance;
}
+ (Manager2 *)sharedInstanceWithDelegate: (id)aDelegate
{
if (aDelegate != nil)
[sharedInstance setDelegate:aDelegate];
return sharedInstance;
}
一个简单的init然后,当我得到实例时发送委托。