How to use delegation (or pass messages) from clas

2019-05-14 18:37发布

问题:

I have a class method that gets called by a view controller. I want the view controller to be aware of when the class method has finished its tasks (it has threads on it).
I think I should use delegation, but I need an id delegate, and I can't call it by self.delegate, because there is no self in a class method.

How should I do this?
Thanks!

回答1:

You can store a delegate at class-level (even separate from an object-level delegate), but it sounds a bit fishy to me. Here's how you'd 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

To actually use this code, you simply set the class-level delegate like an object-level delegate and wait for it to be called (you need to decide when myCleanupClassMethod is invoked):

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