iOS协议/代表混淆? [英] iOS Protocol / Delegate confusion?

查看:91
本文介绍了iOS协议/代表混淆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

All this is my first post and I will try to be as precise as possible. I have read numerous articles about protocol / delegate implementation for iOS but all examples failed. Let say I have A and B controller and want to send data from A to B. A.h

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

@interface ViewController
{
__weak id <exampleprot> delegate
}

-
某些程序$
b $ b我尝试推送

-- A.m in some procedure I try to push

[delegate  examplemethod:@"test"]






Bh


B.h

@interface test2 : UiViewcontroller <exampleprot>

和Bm实现方法 - (void)exampledmethod:(NSString *)e1;

and in B.m implement method -(void) exampledmethod:(NSString *) e1;

所以我做错了什么?

推荐答案

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

Basically this is the example of custom delegates and it is used for sending messages from one class to another. So for sending message in another class you need to first set the delegate and then conforming the protocol in another class as well. Below is the example:-

Bh class

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

Bm class

- (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];
}

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

Am class

 //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 

    }

这篇关于iOS协议/代表混淆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆