简单的自定义委托没有被调用

时间:2013-12-10 10:20:29

标签: ios iphone ios7

让我们看看你们是否可以在这里找到错误...因为我现在真的被困住了。

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 个答案:

答案 0 :(得分: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];

答案 1 :(得分:2)

委托方法managerDidFinishUpdating:init内调用。在调用init后,您将自己设置为委托。

也许initWithDelegate:方法会有所帮助。

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

答案 2 :(得分: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];