【问题标题】:iOS Protocol / Delegate confusion?iOS 协议/委托混淆?
【发布时间】:2013-10-30 10:04:06
【问题描述】:

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

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

@interface ViewController
{
__weak id <exampleprot> delegate
}

-- 是 在某些程序中 我试着推

[delegate  examplemethod:@"test"]

B.h

@interface test2 : UiViewcontroller <exampleprot>

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


所以我做错了什么?

【问题讨论】:

  • 你想做什么...?
  • 您在分配代表吗?喜欢objectOfA.delegate = objectOfB?如果不是财产,还有其他方式吗?
  • 我想通过协议/委托将数据从 A 发送到 B(通过示例方法传递字符串)控制器,但是我缺少一些步骤,并且在阅读了很多网上的文章后,我可以不明白我做错了什么?

标签: ios objective-c


【解决方案1】:

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

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 

    }

【讨论】:

  • 您的解释非常好,我混合了将协议放在哪里,如果将 A 发送到 B-那么协议应该在 B 中-谢谢,其他的,我尝试了您的示例,但是 Receive=null还在吗?
  • 你能告诉我你的代码吗?你在哪里设置委托??
  • 我在 A.m 的 viewDidLoad 中添加它
  • 在您的操作方法或其他方法中设置,尽管在加载方法中设置,
  • 我试过了,还是一样,总是NULL?你有什么建议?
【解决方案2】:

如果你想从 A 向 B 发送数据,那么你应该在 B 中定义一个返回类型的委托。在B中,会有委托声明:

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

然后在A中,实现这个方法。在上午,你需要有

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

然后在 B 中,您需要做的就是使用该委托从 A 中获取您想要的。在 B.m 中,您有

- (void)methodInB {
    // Get string from delegate
    self.string = [self.delegate exampleMethod];
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多