IOS应用程序 - 在单独的文件中定义协议

时间:2012-07-14 10:29:14

标签: objective-c ios

我在一个单独的文件(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;

firstViewController.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没有调用协议美联储。为什么会这样?任何建议将不胜感激。

1 个答案:

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

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

希望有所帮助。