如何从类方法中使用委派(或传递消息) [英] How to use delegation (or pass messages) from class methods

查看:152
本文介绍了如何从类方法中使用委派(或传递消息)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类视图控制器调用的类方法。我希望视图控制器知道什么时候类方法完成了任务(它有线程)。

我想我应该使用委托,但我需要一个 id委托,我不能通过 self.delegate 调用它,因为类方法中没有自己。



我该怎么做?

谢谢!

解决方案

您可以在类级别(甚至与对象级委托分开)中存储代理,但对我来说听起来有点腥。你可以这样做:



在你的头文件中:

  @interface SomeClass:SomeBaseClass 
{
...
}

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

@end

在您的实现文件中:

  @implementation SomeClass 
...

static id< SomeDelegateProtocol> _classDelegate = nil;

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

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

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

@end

为了真正使用这段代码,你只需像类对象级别的委托一样设置类级别的代理,并等待它被调用(您需要确定何时调用 myCleanupClassMethod ):

  //项目中的其他地方
[SomeClass setClassDelegate:self];


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!

解决方案

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];

这篇关于如何从类方法中使用委派(或传递消息)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆