一些帮助将不胜感激。
我有这个简单的项目用于测试目的:
http://dl.dropbox.com/u/10101053/testDelegate.zip
我想在委托方法中传递NSString但是这段代码不起作用。
testDelegateViewController.h
@protocol testDelegateViewControllerDelegate;
@interface testDelegateViewController : UIViewController {
id<testDelegateViewControllerDelegate> delegate;
IBOutlet UIButton *button;
}
@property (nonatomic, assign) id<testDelegateViewControllerDelegate> delegate;
@property (nonatomic, retain) IBOutlet UIButton *button;
- (void)pass;
@end
@protocol testDelegateViewControllerDelegate
- (void)passSomeToDelegate:(NSString *)some;
@end
testDelegateVewController.m
#import "testDelegateViewController.h"
@implementation testDelegateViewController
@synthesize delegate, button;
- (void)pass
{
NSLog(@"Button Pressed");
[self.delegate passSomeToDelegate:@"some"];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
[button addTarget:self action:@selector(pass) forControlEvents:UIControlEventTouchUpInside];
}
//rest of code
AppDelegate.h
#import "testDelegateViewController.h"
@interface AppDelegate : NSObject <UIApplicationDelegate, testDelegateViewControllerDelegate> {
}
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window=_window;
@synthesize viewController=_viewController;
#pragma mark Delegate Method
- (void)passSomeToDelegate:(NSString *)some
{
NSLog(@"%@", some);
}
//rest of code
但是在我的控制台中,按下按钮时不会打印任何内容。
由于
答案 0 :(得分:6)
您忘记设置代理人了。您可以使用application:didFinishLaunchingWithOptions:
方法设置委托。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.viewController.delegate = self;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
我添加了self.viewController.delegate = self;
来设置代理。