Objective-C++ block vs Objective-C block

2019-06-24 04:31发布

In Objective-C I have the valid code:

TestTwo.h:

@interface TestTwo : NSObject
-(void)test;
@end

TestTwo.m:

@implementation TestTwo
-(void)test
{
    void (^d_block)(void) = 
    ^{
        int n;
    };
}
@end

What I really want is an Objective-C++ class that defines a method similar to test. This is simplification, but illustrates the intent. So, in Objective-C++ I have:

Test.h:

class Test
{
public:
    void TestIt();
};

Test.mm:

#include "Test.h"

void Test::TestIt()
{
    void (^d_block)(void) = 
    ^{
        int n;
    };
}

I get the following error:

error: 'int Test::n' is not a static member of 'class Test'.

If I remove int n; there is no error. How do I define n within the block in this context?

2条回答
相关推荐>>
2楼-- · 2019-06-24 04:46

Within the class definition you can add:

private:
static int n;
查看更多
▲ chillily
3楼-- · 2019-06-24 05:07

This is a GCC bug filed under radar #8953986. You can either use Clang/LLVM 2.0+ to compile your code as is, or put your block variables in the global name space (i.e., int ::n) and use GCC. Note that using the global name space in this case is not valid C++ and Clang/LLVM 2.0+ won’t compile it.

查看更多
登录 后发表回答