在哪里设置delegate = self?或者我应该使用不同的设计模式?

时间:2014-12-17 23:04:24

标签: ios objective-c delegates delegation

编辑:为清晰起见而编辑

免责声明:我是新人,非常糟糕。但我已经非常努力地阅读了很多东西来解决这个问题,但我还没有......

我认为我的整个委托模式都可以工作,除了我无法弄清楚如何在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

有人可以告诉我最好的方法吗?感谢您的阅读

1 个答案:

答案 0 :(得分:1)

你问“在哪里设置委托=自我?或者我应该使用不同的设计模式?”。

答案:不要。一个对象永远不应该是它自己的委托。

你的代码非常混乱。

不要将类命名为“Delegate”。代表是一种设计模式。委托的全部意义在于,任何符合特定协议(“说出语言”)的对象都可以作为委托。您不需要知道什么类的对象作为委托,但只是它说出您需要的语言。

类比:当您致电操作员时,您并不关心谁在操作台上工作。你不关心他/她的性别,宗教,种族背景,他们的身高等等。你只关心他们说你的语言。

同样,当您设置委托时,将哪种类型的对象设置为委托并不重要。重要的是作为委托的对象符合该委托的协议。

只要该对象符合UITableViewDelegate协议,表视图就可以将任何对象作为其委托。您通常会将视图控制器视为表视图的委托,但您不必这样做。您可以创建一个管理表视图的自定义类,并将其作为委托。没有“TableViewDelegate”对象类。而是一个UITableViewDelegate协议,任何符合协议的对象都可以作为表视图的委托。

编辑:您的问题令人困惑。我认为你提出的是你的Delegate类会创建一个视图控制器并使自己成为视图控制器的委托。

如果这就是你在说什么,你的想法是倒退的。视图控制器使用Delegate类作为帮助程序类。视图控制器类的任何给定实例都可以创建Delegate类的实例,并根据需要将其设置为委托。您可能一次有3个ViewController实例,每个实例都有自己的Delegate类实例。

因此,ViewController对象是应该创建和设置Delegate实例的对象,如果需要的话:

- (void) viewDidLoad;
{
  self.delegate = [[Delegate alloc] init];
  //other setup here
}
相关问题