2012-10-13 119 views
0

我有这个简单的类如何设置委托

TestViewController.h

#import <UIKit/UIKit.h> 
#import "ClassB.h" 

@protocol TestViewControllerDelegate <NSObject> 

-(void)hello; 

@end 

@interface TestViewController : UIViewController 

@property (nonatomic , weak) id<TestViewControllerDelegate> delegate; 

@end 

TestViewController.m

#import "TestViewController.h" 

@interface TestViewController() 

@end 

@implementation TestViewController 
@synthesize delegate = _delegate; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    /******* WHAT SHOULD I WRITE HERE?!?? *****/ 

    [self.delegate hello]; 

} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 

@end 

而另一个类:

ClassB.h

#import <Foundation/Foundation.h> 
#import "TestViewController.h" 

@interface ClassB : NSObject <TestViewControllerDelegate> 

@end 

ClassB.m

#import "ClassB.h" 
@implementation ClassB 

-(void)hello 
{ 
    NSLog(@"HELLO!"); 
} 

@end 

现在我需要创建和ClassB的实例并设置该实例作为TestViewContoller的代表,但我想不出我需要写什么! 你能帮我吗?

回答

1

你写的是正确的。唯一需要做的其他事情是将ClassB设置为TestViewController的委托。一个通常做的一种方式是ClassB的实例TestViewController,然后将自己作为代表:

在ClassB的:

TestViewController *test = [[TestViewController alloc] init]; 
test.delegate = self; 
+0

我应该在哪里添加这两行代码? ClassB的哪种方法? –

+0

无论你需要什么。这取决于何时需要实例化TestViewController。 – rdelmar

+0

mmmh ..在这种情况下,我不能在Hello方法中编写这些代码行。我是否需要在我的TestViewController的viewDidLoad方法中创建ClassB的实例?在你看来,我如何修改我的代码来做到这一点? –