Retaining ARC objects in c++ classes

后端 未结 2 644
傲寒
傲寒 2021-02-19 12:07

I have some code that must remain as c++, but I need to store objective-c objects in these c++ classes. The objects will not be referenced anywhere else while they are stored h

相关标签:
2条回答
  • 2021-02-19 12:33

    You can call CFRetain and CFRelease under ARC. You are responsible for balancing each CFRetain with a CFRelease, because ARC does not pay any attention to these functions.

    There is no CFAutorelease function. You could perform an autorelease using objc_msgSend(myObject, sel_registerName("autorelease")). The hoops you are jumping through here should be a red flag that you're doing something that's probably wrong.

    Generally it's better under ARC to find a way not to store object references in otherwise-untyped blobs of memory. Note that member variables of C++ objects can be qualified __strong or __weak if you compile them as Objective-C++.

    UPDATE

    The public SDKs of Mac OS X 10.9 and iOS 7.0 include a CFAutorelease function, which you can use even under ARC.

    0 讨论(0)
  • 2021-02-19 12:36

    I had some success using bridge casting when converting some old code to Xcode 4.3. It wouldn't let me bridge directly but I was able to bridge via a void *. I only did this to get some old code working so I can't guarantee it works perfectly.

    struct {
      __unsafe_unretained UIView *view;
    } blah;
    ...
    blah = malloc(sizeof(blah));
    ...
    // Cast the pointer with +1 to retain count
    blah->view = (__bridge UIView *) (__bridge_retained void *) myView;
    ...
    // blah->view can be used as normal
    ...
    // Transfer ownership back to ARC for releasing
    myView = (__bridge_transfer UIView *)(__bridge void *)blah->view;
    
    0 讨论(0)
提交回复
热议问题