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

前端之家收集整理的这篇文章主要介绍了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没有调用协议美联储.为什么会这样?任何建议将不胜感激.

解决方法

首先,正如@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搜索允许您找到关于该主题的大量答案.

希望有所帮助.

原文链接:https://www.f2er.com/c/120223.html

猜你在找的C&C++相关文章