简体   繁体   中英

iOS 8.1.1 casting @“1” as YES and as NO on different devices

I have an authentication routine that retrieves an encrypted JSON document from an server API for an validation routine.

Once the json message is decrypted it is parsed into a NSDictionary.

Starting with iOS 8.1.1 (and not before) we have some devices in which the following parses to YES and in others it parses to NO.

BOOL isValid =  (BOOL)[resp objectForKey : @"IsValid"];

The value of the IsValid property in the json dictionary is { IsValid: "1" } Up to now it has been working fine, since iOS 6, but iOS 8.1.1 broke this on some devices.

I need to understand why this happened, and if there is anything on the device that may cause this issue.

Is there any reason for this and a way to fix it on the device? I don't want to have to do a new release for many reasons.

I am surprised that the cast has ever worked as intended: casting an object to BOOL should result in comparison of the pointer to nil , and returning YES for all non-nil values. In other words, the cast would produce YES if a value is present, be it @0 or @1 , and NO if the value is missing.

To convert based on the value, use boolValue method of NSNumber instead:

BOOL isValid = [[resp objectForKey : @"IsValid"] boolValue];

BOOL is a typedef for signed char . When you cast an object pointer to BOOL , only the low-order 8 bits are preserved. Those 8 bits could be all zero even if the object pointer is not nil , thus a non- nil object pointer could become a false BOOL . (A nil object pointer can't ever become a true BOOL , though.)

This has nothing to do with the OS. It's a completely arbitrary result (which is not the same thing as "random").

That's one of many reasons why such a cast is a terrible idea.

You need to call boolValue on your NSString object. From the docs :

This property is YES on encountering one of "Y", "y", "T", "t", or a digit 1-9—the method ignores any trailing characters. This property is NO if the receiver doesn't begin with a valid decimal text representation of a number.

Duplicate of this post

typecast BOOL always returns false in iOS 8.1.1

Do a google search before asking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM