Using C ++ 11 lambda functions in ObjectiveC ++ ARC - how to do it right?

I have an ObjectiveC ++ project. In the context of ObjectiveC, I use ARC and iPhoneSDK 6. In C ++, I use the C ++ 11 compiler.

Lambda functions in C ++ 11 capture variables with references. This concept is not actually supported by ObjectiveC and the "attempt and error". I came up with the following solution. Are there any pitfalls that I don’t know about?

Is there a better solution to this problem?

typedef std::function<void ()> MyLambdaType; ... // m_myView will not go away. ARC managed. UIView * __strong m_myView; ... // In Objective C context I create a lambda function that calls my Objective C object UIView &myViewReference = *m_myView; MyLambdaType myLambda = [&myViewReference]() { UIView *myViewBlockScope = &myViewReference; // Do something with `myViewBlockScope` } .. // In C++11 context I call this lambda function myLambda(); 
+7
source share
1 answer

The simplest task would be to allow the lambda to capture the pointer variable of the m_myView object (I assume from your fragment that it is a local variable) and usually use it inside the lambda:

 MyLambdaType myLambda = [m_myView]() { // Do something with `m_myView` } 

The only concern is m_myView memory m_myView . To be generally correct, a lambda must save m_myView when it is created, and release it when it is destroyed (just like blocks do, because lambda can be used in an area where m_myView does not exist).

Reading through ARC docs, I don’t see this situation specifically mentioned, but I believe that it should handle it properly, because (1) the captured lambda C ++ 11 variables are stored as fields of an anonymous class that are initialized with the captured value when building a lambda, and (2) ARC correctly handles saving and releasing fields of an Objective-C object of C ++ classes when building and destroying. Unless he says something specifically about lambdas to the contrary, or there is a compiler error, I see no reason why this should not work.

+12
source

All Articles