2012-10-13 117 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的實例?在你看來,我如何修改我的代碼來做到這一點? –