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.
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) {
// ...
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With