简体   繁体   中英

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. But as you use (weak) I assume you use ARC.

If you use protocols at all then you do not need to fully qualify MyDelegateClass* <MyProtocol> . id <MyProtoco> should do. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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