简体   繁体   English

考虑到我不能使用属性,如何为类(不是实例)指定委托?

[英]How do I designate a delegate for a class (not an instance) considering I can't use properties?

I've defined a protocol for my custom class, and now I want to give it a delegate. 我为自定义类定义了一个协议,现在我想给它一个委托。 The class will not be instantiated, only used for its class methods. 该类不会实例化,仅用于其类方法。 The delegate class, however, has been instantiated and assigned to a constant. 但是,委托类已实例化并分配给一个常量。 If I was instantiating the class, I would let it refer to its delegate like this: 如果我要实例化该类,则可以让它像这样引用其委托:

@property (weak) MyDelegateClass <MyProtocol> *delegate;

But because I'm not instantiating the class, I can't give it properties. 但是因为我没有实例化该类,所以无法赋予它属性。 So how do I refer to its delegate? 那么,我该如何称呼它的代表呢? A getter method? 吸气方法? Something like this? 像这样吗 Do I also need to define a setter? 我还需要定义一个二传手吗?

+ (<MyProtocol>MyDelegateClass *)delegate;

What's the syntax here? 这里的语法是什么?

@interface NeverInstanciatedClass

+ (MyDelegateClass *) delegate;
+ setDelegate: (MyDelegateClass* <MyProtocol>) delegate;

@end

@implementation 

static MyDelegateClass <MyProtocol> *_delegate;

+ (MyDelegateClass *) delegate {
    return _delegate;
}

+ setDelegate: (MyDelegateClass* <MyProtocol>) delegate {
    _delegate = delegate;
}

@end

(from scratch - never compiled nor syntax checked) (从头开始-从未编译,也没有语法检查)

If you don't ARC then you may want to add some memory management. 如果您不使用ARC,则可能需要添加一些内存管理。 But as you use (weak) I assume you use ARC. 但是当您使用(weak)我假设您使用的是ARC。

If you use protocols at all then you do not need to fully qualify MyDelegateClass* <MyProtocol> . 如果您完全使用协议,则不需要完全限定MyDelegateClass* <MyProtocol> id <MyProtoco> should do. id <MyProtoco>应该可以。 I just did that because you did it in your sniplets. 我这样做是因为您在代码段中做到了。 As you access methods (and you should then access methods only) that are declared in the protocol, there is no need to even know what type of object it is. 当您访问协议中声明的方法(然后应该只访问方法)时,甚至不需要知道它是什么类型的对象。 All you (and the compiler) need to know is that it implements the protocol. 您(以及编译器)只需要知道它实现了协议即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM