3

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)

Community
  • 1
  • 1
Tony
  • 36,591
  • 10
  • 48
  • 83

1 Answers1

5

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).

ipmcc
  • 29,581
  • 5
  • 84
  • 147