[英]Delegate pattern in a singleton does not work
20140115 updated: with working code 20140115更新:具有工作代码
I have a Singleton where I want to use the delegate pattern. 我有一个Singleton,我想使用委托模式。 When I call the methode with the delegate I get not notified.
当我与委托调用方法时,不会得到通知。
Where is my error? 我的错误在哪里? How can I get the delegate pattern to work with
didComposition
? 我怎样才能使委托模式与
didComposition
一起didComposition
?
Below my debugger and code, the important parts: 在我的调试器和代码下面,重要部分是:
2014-01-15 14:31:09.703 Foobar[5854:70b] -[WebApi sandbox] [Line 42] Sandbox call
2014-01-15 14:31:09.707 Foobar[5854:70b] -[WebApi getSurroundStream] [Line 67] Surround Stream call
#import "AFHTTPRequestOperationManager.h"
@class WebApi;
@protocol WebApiDelegate <NSObject>
-(void)didComposition;
@end
@interface WebApi : AFHTTPRequestOperationManager <SingletonDelegate>
@property (assign, nonatomic)id<WebApiDelegate> delegate;
+(WebApi*)sharedInstance;
-(void)sandbox;
-(void)doSurroundComposition;
@end
#import "WebApi.h"
#define kApiHost @"http://192.168.0.1"
@implementation WebApi
-(WebApi*)initWithBaseURL:url {
self = [super init];
if (self != nil) { }
return self;
}
#pragma mark - Singleton methods
+(WebApi*)sharedInstance
{
static WebApi *sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:kApiHost]];
});
return sharedInstance;
}
-(void)sandbox {
DLog(@"Sandbox called");
// Do AFNetworking Stuff
}
-(void)doSurroundComposition {
[self sandbox];
DLog(@"do surround composition");
[self.delegate performSelector:@selector(didComposition)];
}
@end
#import <UIKit/UIKit.h>
#import "Lokation.h"
#import "WebApi.h"
@interface SurroundViewController : UICollectionViewController <LokationDelegate, WebApiDelegate>
@property (strong, nonatomic) Lokation *lokation;
@end
#import "SurroundViewController.h"
#import "SWRevealViewController.h"
@interface SurroundViewController ()
@end
@implementation SurroundViewController
-(id)init
{
self = [super init];
if (self) {
// Custom initialization
self.lokation = [[Lokation alloc] init];
self.lokation.delegate = self;
[self.lokation getLocation];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[WebApi sharedInstance].delegate = self;
[[WebApi sharedInstance] doSurroundComposition];
}
-(void)didComposition {
DLog(@"did load composition"); // will not be called!
}
@end
When you call [WebApi sharedInstance]
for the first time, you then need to set the delegate to something. 首次调用
[WebApi sharedInstance]
时,需要将委托设置为某种形式。 Currently (in the code you show) you aren't setting any delegate. 当前(在显示的代码中)您没有设置任何委托。 So when the shared instance tries to call the delegate it is simply a no-op.
因此,当共享实例尝试调用委托时,它只是一个空操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.