3

I'm trying to convert a project to ARC. The project has a Directed Acyclic Word Graph, which basically means lots of double indirection pointers everywhere.

This is proving quite a challenge to convert to ARC, and one issue in particular has me currently stumped.

Here's the scenario.

Let's say you have an NSString *:

NSString *b = [[NSString alloc] initWithString:@"hello"];

You also have a double indirection type:

__unsafe_unretained NSString **a;

You want to assign one to the other as follows:

    a = &b;

This gives a conversion error:

error: assigning 'NSString *__strong *' to 'NSString *__unsafe_unretained *' changes retain/release properties of pointer

Changing b to __unsafe_unretained doesn't work. I've also tried the various bridging casts. Am I missing something obvious here?

Any ideas?

Thanks!

Max MacLeod
  • 26,115
  • 13
  • 104
  • 132

1 Answers1

5

You can use a pointer-to-const-pointer to avoid memory management issues:

__attribute__((objc_precise_lifetime)) NSString *b = [[NSString alloc] initWithString:@"hello"];
NSString *const*a;
a = &b;

you need to use objc_precise_lifetime to make b available for the whole context (ARC may release b after last reference)

EDIT: This can also be used (but be aware of managing your double pointer)

NSString *b = [[NSString alloc] initWithString:@"hello"];
NSString *__strong*a;
a = &b;
Martin Ullrich
  • 94,744
  • 25
  • 252
  • 217
  • is there a way to do it without the const qualifier? I need to assign values to *a ? – Max MacLeod Mar 06 '12 at 11:45
  • 1
    NSString *b = [[NSString alloc] initWithString:@"hello"]; NSString *__strong*a; a = &b; – Martin Ullrich Mar 06 '12 at 11:49
  • 1
    but i don't think this is a good reason because ARC will not "memory manage" a pointer to a pointer (this is why ** defaults to *__autoreleasing*) – Martin Ullrich Mar 06 '12 at 11:50
  • awesome thanks. One last question! Do you know of any good references to read up on ARC's behaviour with pointers to pointers? I.e. how did you not about the default there? – Max MacLeod Mar 06 '12 at 12:11
  • 1
    the most complete doc seems to be the compiler documentation: http://clang.llvm.org/docs/AutomaticReferenceCounting.html – Martin Ullrich Mar 06 '12 at 13:16