Obj-C:我正在努力减少代表人数,但是我搞砸了一些东西 [英] Obj-C: I'm trying to understang delegates, but I'm messing something

查看:156
本文介绍了Obj-C:我正在努力减少代表人数,但是我搞砸了一些东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了花一个MyGarden的例子,但是当我尝试做类似的事情时,它不起作用。我的代码:

I saw the example with Flower an MyGarden, but when I try to make something similar it doesn't work. My code:

ClassA.h:

#import <Foundation/Foundation.h>

@protocol CommDelegate <NSObject>
@required
-(void)funcB;
@end

@interface ClassA : NSObject
{
    id <CommDelegate> delegate;
}
@property (retain) id delegate;
-(void)funcB;
@end

ClassA.m

#import "ClassA.h"

@implementation ClassA
-(void) start
{
    [[self delegate] funcB];
}
@end

ClassB.h

#import <Foundation/Foundation.h>
#import "ClassA.h"

@interface ClassB : NSObject <CommDelegate>
@end

ClassB.m

#import "ClassB.h"

@implementation ClassB
-(void)funcB
{
    NSLog(@"HELLO!");
}
@end

主要我在做: p>

And in main I'm doing:

ClassA* classa = [[ClassA alloc] init];
[classa start];

有人可以帮助我,告诉我做错什么吗?

Could someone help me, and tell what I'm doing wrong?

推荐答案

代理概述摘要:


  1. 创建一个@protocol您希望从代理人可以调用的方法,但由代理提供。

  2. 在委托人的公开@interface中添加委托@property。

  3. 在委托人的实现中使用委托属性,例如result = [self.delegate methodInProtocol]

  4. 在委托的@implementation中的某个地方设置委托属性:
    delegator.delegate = self;

  5. 在委托中实现协议方法(包括@interface中的<>)

  1. Create a @protocol which is the methods that you wish to be callable from the delegator but are provided by your delegate.
  2. Add delegate @property in delegator's public @interface.
  3. Use delegate property inside delegator's implementation e.g. result = [self.delegate methodInProtocol]
  4. Set the delegate property somewhere in the delegate's @implementation: delegator.delegate = self;
  5. Implement the protocol method(s) in the delegate (include <> on @interface)

代理只是一个指针一个将为您实施必要的方法的对象。在你的情况下,我想你希望classA能够调用funcB方法,但是funcB是由别人实现的。

The delegate is just a pointer to an object that will implement the necessary methods for you. In your case, I think you want classA to be able to call a funcB method, but for that funcB to be implemented by someone else.

需要一个委托在类中的属性想要有另一个类实现这些方法,然后在作为委托的类中,应该将委托属性设置为self。

There needs to be a delegate property in the class that wants to have another class implement these methods and then in the class that is to be the delegate, it should set the delegate property to self.

As其他人注意到,你不设置你的代表。在班级的某个地方,您需要一个

As others have noted, you don't set your delegate. Somewhere in classB you need a

ClassA.delegate = self;

这篇关于Obj-C:我正在努力减少代表人数,但是我搞砸了一些东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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