委托方法不会被调用

时间:2012-03-25 16:04:03

标签: objective-c ios xcode

我完全不习惯从UIView子类调用一个方法,该方法不会被解雇,我感觉我做错了但是在搜索网络后我没有发现任何线索。提前谢谢

这是iPadMainViewController.h文件

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

@interface iPadMainViewController : UIViewController <TouchViewDelegate> 

@property (retain) UIWebView *detailsView;

@end

以及包含方法

的iPadMainViewController.h文件
- (void)MethodNameToCallBack:(NSString *)s
{
    NSLog(@"%@",s);
}

这是TouchView.h文件,应该是

@protocol TouchViewDelegate
- (void)MethodNameToCallBack:(NSString *)s;
@end

@interface TouchView : UIView {
    id<TouchViewDelegate> delegate;
}

@property (nonatomic, assign) id delegate;

@end

这是TouchView.m文件,它应该调用它的委托方法

@implementation TouchView
@synthesize delegate;


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"HELLO FROM INSIDE");

    [[self delegate] MethodNameToCallBack:(NSString *)@"HELLO FROM OUTSIDE"];
}

@end

3 个答案:

答案 0 :(得分:3)

合成委托是不够的,因为它只是创建了getter和setter方法。它不会创建iPadMainViewController的实例。

因此,在创建TouchView的实例后,您应该将iPadMainViewController的实例指定为委托。

iPadMainViewController *controller = [[iPadMainViewController alloc] init...
// ...
TouchView *touchView = [[TouchView alloc] init...
// ...
touchView.delegate = controller;

或者在iPadMainViewController的viewDidLoad方法中:

- (void)viewDidLoad
{
    // ...
    self.touchView.delegate = self;
}

答案 1 :(得分:0)

在实例化TouchView实例后进行检查,是否已分配其委托?

答案 2 :(得分:0)

增强你的touchesBegan实现,以便进一步调试:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"HELLO FROM INSIDE");
    NSLog(@"our delegate is set towards: %@", delegate);
    ...
}

它是否在第二个日志记录语句中记录了一些有用的东西?

我认为它打印nil,这将是你问题的根本原因;你忘了分配代表了。