Objective-C++ block vs Objective-C block

拜拜、爱过 提交于 2019-12-23 15:07:14

问题


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?


回答1:


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.




回答2:


Within the class definition you can add:

private:
static int n;


来源:https://stackoverflow.com/questions/6525928/objective-c-block-vs-objective-c-block

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