Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion of a non-Objective-C pointer type void* to NSString*__strong* is disallowed with ARC

I got the above error when migrate to ARC. Here is the code:

static NSString *cashBalanceKeyPath = @"test";

...

[xxx forKeyPath:cashBalanceKeyPath options:NSKeyValueObservingOptionNew context:&cashBalanceKeyPath];

...

-(void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

    if (&cashBalanceKeyPath == context)   < error here
    {
      ...
    }

When I used bridge:

if (&cashBalanceKeyPath == (__bridge NSString *)context)

I got the error: Comparison of distinct pointer types (NSString *__strong* and NSString *)

How can I make the conversion? Thanks in advance.

like image 564
user2543991 Avatar asked Jul 02 '13 19:07

user2543991


3 Answers

I can't tell you exactly why, but you don't get a warning or error if you swap the order of the comparison:

if (context == &cashBalanceKeyPath) {
    // ...      
}
like image 85
Martin R Avatar answered Oct 07 '22 16:10

Martin R


You appear to be using the address of a variable as a unique tag, so there are no memory management/ownership issues here. To do the address comparison cast the address of the variable to void:

if ((void *)&cashBalanceKeyPath == context)

That seems to give the compiler all it needs without any bridge cast.

like image 42
CRD Avatar answered Oct 07 '22 16:10

CRD


If you strip out the __strong in the error message, it's clearer what's going on:

Comparison of distinct pointer types (NSString ** and NSString *)

&cashBalanceKeyPath is a pointer to an NSString object, or a NSString**, while context is being cast to an NSString*, or a plain NSString object (which it isn't).

So to fix the problem, change the cast to be (NSString * const *), the const is apparently required to appease ARC.

like image 1
cobbal Avatar answered Oct 07 '22 15:10

cobbal