delegate = nil,在VC之间传递信息问题

时间:2013-03-08 03:13:10

标签: ios objective-c delegates

我刚开始学习obj-c,我对代表有疑问。我知道在SOF上有很多类似的线程,但我一直在寻找并且真的没有得到我的问题(可能因为我是初学者)。这是我的问题:我想使用自己的委托并将SlaveClass中的信息传递给MainClass。在buttonDidClick:action中的SlaveClass中,我声明了一个等于NIL的委托。即使我不知道我应该从哪里开始寻找错误。提前感谢任何类型的建议。这是我的代码,它引用了委托:

SlaveClass.h

@protocol slaveDelegate <NSObject>

 -(void)transferNameDidClick:(NSString *)text;

@end
// --------------------------------------------------------------------------------
@interface SlaveClass : UIViewController
@property (nonatomic, strong) id <slaveDelegate> myOwnDelegate;
@end

SlaveClass.m(此处显示为NIL)

-(void)buttonDidClick:(id)sender
{
    if ([_myOwnDelegate respondsToSelector:@selector(transferNameDidClick:)])
    {
        [_myOwnDelegate transferNameDidClick:(_textField.text)];
    }
}

MainClass.h

@interface MainClass : UIViewController <slaveDelegate>
@end

MainClass.m

-(void)transferNameDidClick:(NSString *)text
{
    SlaveClass *delegate = [[SlaveClass alloc] init];
    [delegate setMyOwnDelegate:self];
    [_label setText:text];
    NSLog(@"text: %@",text);
}

2 个答案:

答案 0 :(得分:0)

您将代表设置在错误的位置。您必须在转到slaveClass

之前设置委托

<强> mainClass.m
像这样出现奴隶视图控制器

SlaveClass *slaveClass = [[SlaveClass alloc] init]
[slaveClass setMyOwnDelegate:self];
[self presentViewController:slaveClas animated:YES completion:nil]; 


-(void)transferNameDidClick:(NSString *)text
{
 // This is the method getting called by the slaveClass. So it should know the delegate to call this. 
[_label setText:text];
NSLog(@"text: %@",text);
}

答案 1 :(得分:0)

设置您委派自定义委托方法。你错误地设置了委托显示nil的自定义委托方法。像这样使用。

主类.M

-(IBAction)nextView
{
    nextView = [[ViewController2 alloc]init];
    nextView.myOwnDelegate = self;
    [self presentViewController:nextView animated:YES completion:nil];


}

-(void)transferNameDidClick:(NSString *)text;
{
    NSLog(@"Value from Slave Delegate %@",text);
}

SlaveClass.h

@protocol slaveDelegate <NSObject>

 -(void)transferNameDidClick:(NSString *)text;

@end
// --------------------------------------------------------------------------------
@interface SlaveClass : UIViewController
@property (nonatomic, strong) id <slaveDelegate> myOwnDelegate;
@end

SlaveClass.m

-(void)buttonDidClick:(id)sender
{
    if ([_myOwnDelegate respondsToSelector:@selector(transferNameDidClick:)])
    {
        [_myOwnDelegate transferNameDidClick:(_textField.text)];
    }
}