How to get the address of an objective c object into a void * volatile * under ARC?

ぐ巨炮叔叔 提交于 2020-01-04 04:04:07

问题


I have a simple objective c object

NSManagedObjectContext * moc = nil

Now I need to pass it into a function in an ARC environment that accepts parameter of type

void *volatile * value

I tried

&((__bridge void *)moc))

but I get the following compiler error

Address expression must be lvalue or a function pointer

I also tried

void ** addr = (__bridge void **)(&moc);

But I get the error

Incompatible types casting 'NSManagedObjectContext * __strong *' to 'void **' with a __bridge cast

Is there any way to first cast and then get the address of the casted pointer?

EDIT

To be more specific, I'm trying to implement the singleton pattern described in another stackoverflow question, but I'm having trouble feeding the address of the objective c NSManagedObjectContext object into the third argument of the following function in an ARC environment.

OSAtomicCompareAndSwapPtrBarrier(void *__oldValue, void *__newValue, void *volatile *__theValue)


回答1:


Another modern singleton pattern I've been seeing/using a lot in the modern era uses GCD's dispatch_once. You asked directly about pointer casting for ARC (and more on that below), but in terms of filling your actual need, why not just do this with GCD? Like this:

+ (NSFoo*)sharedFoo
{
    static dispatch_once_t pred;
    static NSFoo* sFoo;
    dispatch_once(&pred, ^{ sFoo = [[NSFoo alloc] init]; } );
    return sFoo;
}

As you can see if you go look at the source for dispatch_once, GCD implements the same pattern you're seeking to implement here. GCD gets around the problem you're having by not using an ARC-tracked pointer as the thing it CompareAndSwaps, but rather using a surrogate value (here pred), so even if you have some aversion to using GCD for your singleton, you might consider mimicking their approach and using a surrogate.

That said, if you just use GCD for your case, you don't ever have to worry about stuff like gnarly ARC pointer casting. You can also be reasonably sure that the GCD implementation will behave consistently across multiple platforms/architectures (MacOS/iOS).



来源:https://stackoverflow.com/questions/8671784/how-to-get-the-address-of-an-objective-c-object-into-a-void-volatile-under-a

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