How to use delegation (or messaging) from class methods

I have a class method that is called by the view controller. I want the view manager to know when the class method has completed its tasks (there are threads on it).
I think I should use delegation, but I need it id delegate, and I can’t call it self.delegate, because I am not in the class method.

How should I do it?
Thank!

+3
source share
1 answer

You can store the delegate at the class level (even separately from the delegate at the object level), but for me this is a little suspicious. Here's how you do it:

In your header file:

@interface SomeClass : SomeBaseClass
{
...
}

...
+ (id<SomeDelegateProtocol>)classDelegate
+ (void)setClassDelegate(id<SomeDelegateProtocol>) delegate
+ (void)myCleanupClassMethod

@end

In your implementation file:

@implementation SomeClass
...

static id<SomeDelegateProtocol> _classDelegate = nil;

+ (id<SomeDelegateProtocol>)classDelegate
{
    return _classDelegate;
}

+ (void)setClassDelegate(id<SomeDelegateProtocol> delegate
{
    _classDelegate = delegate;
}

+ (void)myCleanupClassMethod
{
    if ([_classDelegate respondsToSelector:@selector(theDelegateMethod:)])
    {
        [_classDelegate theDelegateMethod:something];
    }
}

@end

, , , ( , myCleanupClassMethod):

// Somewhere else in the project
[SomeClass setClassDelegate:self];
+3

All Articles