我很难绕过代表们。我尝试用一个简单的例子来教自己,但它只是没有用。
我的简单测试有两个类。 ClassA和ClassB。 ClassA具有委托定义。以及调用包含委托方法调用(-(void)buttonHasBeenPressed:(id)sender
)的方法(-(void)buttonPressed
)的按钮。设置了ClassB(我认为)来监听ClassA委托,当调用-(void)buttonHasBeenPressed:(id)sender
时,它会写入控制台。
这是AppDelegate:
·H
#import <UIKit/UIKit.h>
@interface DelegateTestAppDelegate : NSObject <UIApplicationDelegate> {
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end
的.m:
#import "DelegateTestAppDelegate.h"
#import "ClassA.h"
@implementation DelegateTestAppDelegate
@synthesize window=_window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
ClassA *classA = [[ClassA alloc] init];
[self.window addSubview:[classA view]];
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
return YES;
}
- (void)dealloc
{
[_window release];
[super dealloc];
}
@end
这是ClassA:
·H
#import <UIKit/UIKit.h>
@protocol ClassADelegate <NSObject>;
-(void)buttonPressed;
@end
@interface ClassA : UIViewController {
id <ClassADelegate> delegate;
}
@property (retain) id <ClassADelegate> delegate;
-(void)buttonHasBeenPressed:(id)sender;
@end
的.m:
#import "ClassA.h"
@implementation ClassA
@synthesize delegate;
-(id)init {
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil {
return [self init];
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(buttonHasBeenPressed:) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"hola" forState:UIControlStateNormal];
button.frame =CGRectMake(50, 200, 100, 20);
[self.view addSubview:button];
}
-(void)buttonHasBeenPressed:(id)sender {
[self.delegate buttonPressed];
NSLog(@"button has been pressed");
}
@end
这是ClassB:
·H
#import <UIKit/UIKit.h>
#import "ClassA.h"
@interface ClassB : UIViewController <ClassADelegate> {
}
@end
的.m:
#import "ClassB.h"
@implementation ClassB
-(id)init {
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil {
return [self init];
}
-(void)buttonPressed {
NSLog(@"delegating!");
}
@end
预期的结果是“按下按钮”和“委派!”单击“hola”按钮时写入控制台。
感谢您的帮助...... 肖恩
答案 0 :(得分:1)
您的ClassB的实例在哪里?我在您发布的代码中找不到它。 另外,在哪里将实例设置为ClassA作为其委托?我也找不到它。
如果你不做这两件事,你的代表将永远不会被调用。
答案 1 :(得分:1)
您忘了将委托设置为符合 ClassADelegate 协议的类,此处应该是 ClassB 的对象