我在一个单独的文件(myProtocol.h)中定义了一个协议.这是它的代码:
#import <Foundation/Foundation.h>
@protocol myProtocol <NSObject>
-(void) loadDataComplete;
@end
Run Code Online (Sandbox Code Playgroud)
现在我想调用这个方法,所以我做了以下代码:
firstViewController.h:
#import "myProtocol.h"
@interface firstViewController : UIViewController{
id <myProtocol> delegate;
}
@property (retain) id delegate;
-(void) mymethod;
Run Code Online (Sandbox Code Playgroud)
firstViewController.m
@implementation firstViewController
@synthesize delegate;
- (void)viewDidLoad {
[self mymethod];
}
-(void) mymethod {
//some code here...
[delegate loadDataComplete];
}
Run Code Online (Sandbox Code Playgroud)
我有另一个文件,其中也使用协议:
secondViewController.h:
#import "myProtocol.h"
@interface secondViewController : UIViewController<myProtocol>{
}
Run Code Online (Sandbox Code Playgroud)
secondViewController.m:
-(void) loadDataComplete{
NSLog(@"loadDataComplete called");
}
Run Code Online (Sandbox Code Playgroud)
但我的secondViewController没有调用协议美联储.为什么会这样?任何建议将不胜感激.
Lor*_*o B 14
首先,正如@Abizern建议的那样,尝试重新格式化代码.使用大写字母表示课程.这里说这个解答你的答案.
这是协议.我会这样命名,FirstViewControllerDelegate因为实现该对象的类是一个委托FirstViewController.
#import <Foundation/Foundation.h>
@protocol MyProtocol <NSObject>
- (void)doSomething;
@end
Run Code Online (Sandbox Code Playgroud)
这是SecondViewController.
#import <UIKit/UIKit.h>
#import "MyProtocol.h"
@interface SecondViewController : UIViewController <MyProtocol>
@end
@implementation SecondViewController
// other code here...
- (void)doSomething
{
NSLog(@"Hello FirstViewController");
}
@end
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
为了完整起见,请务必了解委托模式的含义.Apple doc是你的朋友.您可以查看协议和委托的基础知识,以获得参数的基本介绍.此外,SO搜索允许您找到关于该主题的大量答案.
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
5250 次 |
| 最近记录: |