iand675
iand675

Reputation: 1118

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

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?

Upvotes: 7

Views: 2531

Answers (2)

Jacob Relkin
Jacob Relkin

Reputation: 163228

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.

Upvotes: 17

kennytm
kennytm

Reputation: 523184

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

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

Upvotes: 2

Related Questions