2013-12-10 57 views
1

讓我們看看你們是否可以在這裏找到錯誤...因爲我現在真的被卡住了。簡單的自定義代理沒有被調用

DBManager.h

@protocol DBManagerDelegate <NSObject> 
@optional 
- (void) managerDidFinishUpdating:(id)controller; 
@end 
@interface DBManager : NSObject 
@property (strong, nonatomic) id <DBManagerDelegate> delegate; 
- (id) init; 
@end 

DBManager.m

#import "DBManager.h" 
@implementation DBManager 
- (id)init { 
    self = [super init]; 
    if (self) { 
     [[self delegate] managerDidFinishUpdating:self]; 
    } 
    return self; 
} 

UIViewController.h

#import <UIKit/UIKit.h> 
#import "DBManager.h" 
@interface DBViewController : UIViewController <DBManagerDelegate> 
@property (nonatomic, retain) DBManager *manager; 
@end 

UIViewController.m

#import "DBViewController.h" 
@implementation DBViewController 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
_manager = [[DBMataroManager alloc] init]; 
    [_manager setDelegate:self]; 
} 
- (void)managerDidFinishUpdating:(id)controller { 
    NSLog(@"Manager did finish"); 
} 
@end 

回答

3
You should write like this, 

- (id)initWithDelegate:(id)delegate { 
    self = [super init]; 
    if (self) { 
     _delegate = delegate; 
     [_delegate managerDidFinishUpdating:self]; 
    } 
    return self; 
} 

//Call it as follow 
_manager = [[DBManager alloc] initWithDelegate:self]; 
[_manager setDelegate:self]; 
2

委託方法managerDidFinishUpdating:被內init調用。您在致電init後,將自己設置爲代表。

也許initWithDelegate:方法會有所幫助。

- (instancetype)initWithDelegate:(id< DBManagerDelegate>)delegate { 
self = [super init]; 
if (self) { 
    self.delegate = delegate; 
    [self.delegate managerDidFinishUpdating:self]; 
} 
return self; 
} 
0

您正在嘗試使用委託在init,但是您沒有設置它,直到下一個語句。做到這一點的唯一方法是將代理設置爲init語句的一部分。

-(id)initWithDelegate:(id<DBManageDelegate>)delegate { 
    if ((self = [super init])) { 
    self.delegate = delegate; 
    if (delegate && [delegate respondsToSelector:@selector(managerDidFinishUpdating:)]) { 
     [delegate performSelector:@selector(managerDidFinishUpdating:) withObject:self]; 
    } 
    } 
    return self; 
} 

但是,如果你打算做一些其他的事情經理更新之前,我建議你將所有的init是外面的,也許到updateManager功能這樣

-(void)updateManager { 
    // Do the stuff that updates your manager here 
    if (delegate && [delegate respondsToSelector:@selector(managerDidFinishUpdating:)]) { 
     [delegate performSelector:@selector(managerDidFinishUpdating:) withObject:self]; 
    } 
} 

..稍後在您的應用程序中

_manager = [[DBMataroManager alloc] init]; 
[_manager setDelegate:self]; 
[_manager updateManager]; 
相關問題