5

所有这些都是我的第一篇文章,我会尽量做到准确。我已经阅读了许多关于 iOS 协议/委托实现的文章,但所有示例都失败了。假设我有 A 和 B 控制器,想将数据从 A 发送到 BAh

    @protocol exampleprot <NSObject>
@required
-(void) exampledmethod:(NSString *) e1;
@end

@interface ViewController
{
__weak id <exampleprot> delegate
}

-- 我在某些程序中尝试推动

[delegate  examplemethod:@"test"]

溴化氢

@interface test2 : UiViewcontroller <exampleprot>

并在 Bm 中实现方法 -(void) exampledmethod:(NSString *) e1;


所以我做错了什么?

4

3 回答 3

8

基本上这是自定义委托的示例,它用于将消息从一个类发送到另一个类。因此,要在另一个类中发送消息,您需要首先设置委托,然后在另一个类中也符合协议。以下是示例:-

B.h班级

@protocol sampleDelegate <NSObject>
@required
-(NSString *)getDataValue;
@end
@interface BWindowController : NSWindowController
{
    id<sampleDelegate>delegate;
}
@property(nonatomic,assign)id<sampleDelegate>delegate;
@end

B.m课堂上

- (void)windowDidLoad
{
 //below only calling the method but it is impelmented in AwindowController class
   if([[self delegate]respondsToSelector:@selector(getDataValue)]){
    NSString *str= [[self delegate]getDataValue];
     NSLog(@"Recieved=%@",str);
    }
    [super windowDidLoad];
}

A.h课堂上

@interface AWindowController : NSWindowController<sampleDelegate> //conforming to the protocol

A.m课堂上

 //Implementing the protocol method 
    -(NSString*)getDataValue
    {
        NSLog(@"recieved");
        return @"recieved";
    }
//In this method setting delegate AWindowController to BWindowController
    -(void)yourmethod
    {

    BWindowController *b=[[BWindowController alloc]init];
    b.delegate=self;   //here setting the delegate 

    }
于 2013-10-30T10:20:10.713 回答
0

If you want to send data from A to B, then you should define a delegate in B with return type. In B, there will be delegate declaration:

@protocol example <NSObject>
@required
-(NSString *) exampleMethod;
@end

Then in A, implement this method. In A.m, you need to have

-(NSString *) exampleMethod:(NSString *) e1 {
    // Implementation of this delegate method
    return self.stringYouWantToPassToB
}

Then in B, all you need to do is use that delegate to get what you want from A. In B.m, you have

- (void)methodInB {
    // Get string from delegate
    self.string = [self.delegate exampleMethod];
}
于 2013-10-30T10:28:40.410 回答
0

您需要设置视图控制器的委托属性,从您要发送数据的位置 = 视图控制器到您要发送数据的位置。我认为侯赛因的回答是正确的。您只需要检查您是否以正确的方式进行操作。

于 2013-10-30T13:17:49.203 回答