Is it possible to define a block as a member of a class?

六月ゝ 毕业季﹏ 提交于 2019-12-05 23:22:59

问题


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

Expected specifier-qualifier-list before '(' token

Any ideas how to make this work?


回答1:


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

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

@end

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

typedef NSArray * (^Strategy)(void);

@interface SSTaskStrategy : NSObject {
   Strategy block;
}

@end

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.




回答2:


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

You don't need to put the ( ) around the return type.



来源:https://stackoverflow.com/questions/4148253/is-it-possible-to-define-a-block-as-a-member-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!