9

我在一个单独的文件 (myProtocol.h) 中定义了一个协议。这是它的代码:

#import <Foundation/Foundation.h>

@protocol myProtocol <NSObject>
    -(void) loadDataComplete;
@end

现在我想调用这个方法,所以我做了以下代码:

firstViewController.h

#import "myProtocol.h"

@interface firstViewController : UIViewController{
    id <myProtocol> delegate;
}
@property (retain) id delegate;
-(void) mymethod;

第一视图控制器.m

@implementation firstViewController
@synthesize delegate;

- (void)viewDidLoad {
    [self mymethod];
}

-(void) mymethod {
    //some code here...
    [delegate loadDataComplete];
}

我还有另一个文件,其中也使用了该协议:

secondViewController.h

#import "myProtocol.h"
@interface secondViewController : UIViewController<myProtocol>{
}

secondViewController.m

-(void) loadDataComplete{
    NSLog(@"loadDataComplete called");
}

但我的 secondViewController 没有调用协议方法。为什么会这样?任何建议将不胜感激。

4

1 回答 1

14

首先,正如@Abizern建议的那样,尝试重新格式化您的代码。类使用大写字母。在这里说这个是您回答的解决方案。

这是协议。我会这样命名它,FirstViewControllerDelegate因为实现该对象的类是FirstViewController.

#import <Foundation/Foundation.h>

@protocol MyProtocol <NSObject>

- (void)doSomething;

@end

这是SecondViewController.

#import <UIKit/UIKit.h>
#import "MyProtocol.h"

@interface SecondViewController : UIViewController <MyProtocol>

@end

@implementation SecondViewController

// other code here...

- (void)doSomething
{
    NSLog(@"Hello FirstViewController");
}

@end

这是FirstViewController.

#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController

// it coud be better to declare these properties within a class extension but for the sake of simplicity you could leave here
// the important thing is to not declare the delegate prop with a strong/retain property but with a weak/assign one, otherwise you can create cycle
@property (nonatomic, strong) SecondViewController* childController;
@property (nonatomic, weak) id<MyProtocol> delegate;

@end

@implementation FirstViewController

// other code here...

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.childController = [[SecondViewController alloc] init];
    self.delegate = self.childController; // here the central point

    // be sure your delegate (SecondViewController) responds to doSomething method
    if(![self.delegate respondsToSelector:@selector(doSomething)]) {

        NSLog(@"delegate cannot respond");
    } else {

        NSLog(@"delegate can respond");
        [self.delegate doSomething];
    }    
}

@end

为了完整起见,请务必了解委托模式的含义。苹果文档是你的朋友。您可以查看the-basics-of-protocols-and-delegates以了解该论点的基本介绍。此外,SO 搜索允许您找到有关该主题的大量答案。

希望有帮助。

于 2012-07-14T11:03:26.317 回答