本文介绍了如何符合自制协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有委托属性的类。任何想成为代表的人都必须遵守协议。我定义了这样的一切:

I have a class with an delegate property. Anyone who wants to be a delegate must conform to a protocol. I defined everything like this:

#import <UIKit/UIKit.h>

@protocol TheDelegateProtocol;

@interface MyClass : UIView {
    id<TheDelegateProtocol> theDelegate;
}

@property (nonatomic, assign) id<TheDelegateProtocol> theDelegate;


@end


@protocol TheDelegateProtocol<NSObject>
@required

- (void)fooBarWithFoo:(CGFloat)foo;
@end

现在疯狂的事情是:我有另一个想成为代表。因此它符合该协议,如下所示:

Now the crazy thing is: I have another class that wants to be the delegate. So it conforms to that protocol, like this:

#import <Foundation/Foundation.h>

@class MyClass; // forward declaration. importet in implementation.
@protocol TheDelegateProtocol; // need forward declaration here, right?

@interface OtherClass : NSObject <TheDelegateProtocol> {
    // ivars
}

@end

我无法让它发挥作用。它说:没有找到协议'TheDelegateProtocol'的定义。好吧,该协议在MyClass中定义,我在实现中导入MyClass。想知道那里有什么问题吗?

I can't get that to work. It says: "No definition of protocol 'TheDelegateProtocol' found". Well, that protocol is defined in MyClass, and I am importing MyClass in the implementation. Any idea what's wrong there?

找出一些东西:在我尝试分配协议的方法中,它告诉我,那是其他类不符合协议。但确实如此!这是没有意义的。我还在标题中添加了协议方法....

Figured out something: In a method where I try to assign the protocol, it is telling me, that OtherClass does not conform to the protocol. But it does! That makes no sense. I also added the protocol method in the header....

推荐答案

我认为你需要# import 定义协议的头文件。如果没有它,编译器如何知道哪些方法可用?

I think you need to #import the header file that defines the protocol. How can the compiler know which methods are available without it?

如果使用另一个类(即作为ivar或作为参数方法)然后你可以使用前向声明。但是如果你是子类,那么你需要 #import

If you use another class (i.e., as an ivar or as a parameter to a method) then you can use a forward declaration. But if you subclass then you need to #import.

这篇关于如何符合自制协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:02