【发布时间】:2015-02-16 15:27:05
【问题描述】:
编辑:为清楚起见进行了编辑
免责声明:我是新手,很糟糕。但是我已经非常努力并阅读了很多东西来弄清楚这一点,但我还没有......
我认为我的整个委托模式都可以工作,但我不知道如何在 MatchLetter 类中将 ViewController 的委托属性设置为 self。原因是我不知道如何在那里调用代码。它不是视图控制器,因此 viewDidLoad 或 prepareForSegue 不起作用。
这就是我所拥有的:
ViewController.h
#import <UIKit/UIKit.h>
@class ViewController;
@protocol letterMatchProtocol <NSObject>
- (BOOL) isLetterMatch:(char) firstLetter;
@end
@interface ViewController : UIViewController
@property (nonatomic, weak) id <letterMatchProtocol> delegate;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
char c = 'a';
// This is the method I want to delegate to MatchLetter, to have a BOOL returned
BOOL returnValue = [self.delegate isLetterMatch:c];
}
@end
MatchLetter.h
#import <Foundation/Foundation.h>
#import "ViewController.h"
@interface Delegate : NSObject <letterMatchProtocol>
@end
MatchLetter.m
#import "MatchLetter.h"
@implementation Delegate
// this is the code I think I need to run here, to set the delegate property...
// ViewController *viewController = [ViewController new];
// viewController.delegate = self;
// ... so that isLetterMatch can be run here from ViewController.m
// But I don't know where to put this code, or how to get it to run before the ViewController
// especially since there are no segues or views to load.
- (BOOL) isLetterMatch:(char)firstLetter {
if (firstLetter == 'a') {
return YES;
}
else {
return NO;
}
}
@end
有人可以告诉我最好的方法吗?感谢阅读
【问题讨论】:
-
实际创建
ViewController实例的代码在哪里?通常你会在那个时候设置它的delegate。 -
仅供参考 - 将您的班级命名为
Delegate是个坏主意。您可能会有其他“代表”课程。给它一个更具描述性的名称。 -
为什么你的视图控制器不是代理?正确的做法通常是让视图控制器成为委托。
-
“我想我明白你必须在实际的委托类中将委托设置为自我,而不是类的实例。” ???你认为有什么不同? (并且您没有在委托类中设置
delegate,而是在委托所服务的类中设置它。) -
rmaddy,感谢您的建议。我在 MatchLetter.m 中添加了创建 ViewController 实例的代码,注释掉了。我不知道调用哪个方法,甚至不知道如何进入 MatchLetter.m。这是我真正的问题
标签: ios objective-c delegates delegation