Search code examples
iosobjective-cxcode632-bit

(BOOL)strstr() failed in a 32-bit iOS device


i use strstr determine whether contains a string, and then use the results strongly to a BOOL type,for example:

BOOL result = (BOOL)strstr(aString, "test");

When aString contains "test" string in a 32-bit iOS device can appear sometimes the result is NO. But the strstr(aString, "test") returns the address correctly.


Solution

  • Depending on the architecture, BOOL may be typedef'd to unsigned char. That's just 8 bits. When you cast a pointer to a BOOL, you may be getting just the low 8 bits from the pointer. If those bits were all 0, then the BOOL is false, even if the pointer was not NULL (0).

    In other words, don't do that.

    If you want a boolean value, use strstr(aString, "test") != NULL or even !!strstr(aString, "test").