是否可以将块定义为类的成员? [英] Is it possible to define a block as a member of a class?

查看:71
本文介绍了是否可以将块定义为类的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Objective-C中实现一个非常简单的策略类,该策略类允许内联定义策略,而不是通过继承进行定义.目前,我的代码如下:

I'm trying to implement a very simple strategy class in Objective-C that allows for strategies to be defined inline instead of being defined through inheritance. Currently my code looks like this:

@interface SSTaskStrategy : NSObject {
    (NSArray *)(^strategy)(void);
}

@end

我认为这可以解决问题,但我遇到了错误

I thought this would work, but I'm getting the error

'('令牌之前的预期specifier-qualifier-list

Expected specifier-qualifier-list before '(' token

有什么想法可以使这项工作成功吗?

Any ideas how to make this work?

推荐答案

您应该在ivar定义中的NSArray *周围加上括号:

You should drop the parentheses around NSArray * in your ivar definition:

@interface SSTaskStrategy : NSObject {
    NSArray * (^strategy)(void);
}

@end

此外,我强烈建议您使用typedef以便更清晰:

Also, I highly recommend that you use a typedef for more clarity:

typedef NSArray * (^Strategy)(void);

@interface SSTaskStrategy : NSObject {
   Strategy block;
}

@end

这使您可以使用名称Strategy来引用此块,而不必每次都希望使用时髦的语法来引用它.

This allows you to reference this block with the name Strategy instead of having to use the funky syntax every single time you wish to reference it.

这篇关于是否可以将块定义为类的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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