2

I have a C++ class in my Objective C ARC project. The class is derived from a pure C++ class and adds a platform specific implementation for my iOS project. I want to call Objective C functions and frameworks there.

I implemented the platform specific parts using C++11 lambda functions. Can I do it that way? Any hidden pitfalls (especially because my iOS project uses ARC)?

bool MyDerivedCPPClass::getValue(const std::string& stdKey, std::string& stdValue) const
{
    NSString *key = [NSString stringWithUTF8String:stdKey.c_str()];

    // Do ObjC stuff

    if(value)
    {
        stdValue = std::string([value cStringUsingEncoding:NSUTF8StringEncoding]);
        return YES;
    }
    else
    {
        return NO;
    }
}
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Lars Schneider
  • 5,530
  • 4
  • 33
  • 58

1 Answers1

2

It looks fine (generally Objective-C does not interfere with C++), aside from:

  • Why are you defining a lambda just to call it immediately?
  • C++ bool should be true/false, not YES/NO
  • Make sure the thread that this runs on has an autorelease pool
newacct
  • 119,665
  • 29
  • 163
  • 224
  • 1. How would I call Obj-C functions without the lambda construct in that case? 2. It all runs on the main thread, so my `@autoreleasepool { ... )` in the main.m should cover it, right? – Lars Schneider Dec 12 '12 at 21:08
  • @LarsSchneider: 1. Umm... this has nothing to do with Obj-C. Just think about C++ for a moment. How is `return [&] { ...blah blah... }();` any different from just `...blah blah...` directly? 2. Yeah, and more importantly, the main thread's run loop has an autorelease pool per iteration which should cover it. – newacct Dec 12 '12 at 21:18
  • You're absolutely right. How stupid was I for not seeing this. Thanks :-) – Lars Schneider Dec 12 '12 at 21:45