PDA

View Full Version : CFLocaleGetValue strange behaviour




THRESHE
Oct 2, 2008, 08:27 AM
Hi
I want to use CFLocale in my application. But I've encountered a strange problem.

This code doesn't work

CFLocaleRef locale = CFLocaleGetSystem();
CFStringRef cfstr = CFStringCreateCopy(NULL, (CFStringRef)CFLocaleGetValue(locale, kCFLocaleGroupingSeparator));
qDebug()<<CFStringGetCStringPtr(cfstr, kCFStringEncodingMacRoman);
But this does

CFLocaleRef locale = CFLocaleGetSystem();
CFBooleanRef b = (CFBooleanRef) CFLocaleGetValue(locale, kCFLocaleUsesMetricSystem);
qDebug()<< CFBooleanGetValue(b);
Can't understand why :confused:



gnasher729
Oct 2, 2008, 12:07 PM
Hi
I want to use CFLocale in my application. But I've encountered a strange problem.

This code doesn't work

CFLocaleRef locale = CFLocaleGetSystem();
CFStringRef cfstr = CFStringCreateCopy(NULL, (CFStringRef)CFLocaleGetValue(locale, kCFLocaleGroupingSeparator));
qDebug()<<CFStringGetCStringPtr(cfstr, kCFStringEncodingMacRoman);
But this does

CFLocaleRef locale = CFLocaleGetSystem();
CFBooleanRef b = (CFBooleanRef) CFLocaleGetValue(locale, kCFLocaleUsesMetricSystem);
qDebug()<< CFBooleanGetValue(b);
Can't understand why :confused:

1. You are using casts (CFStringRef) and (CFBooleanRef). Casts don't change what an object is, they only change what the compiler thinks the object is. This is very dangerous.

2. Read the documentation of CFStringGetCStringPtr. It is documented that the function can return NULL, and it is likely to do so if you ask for MacRoman text.

3. CFBooleanGetValue actually only checks whether the object you pass in is kCFBooleanTrue or not. So if you pass in kCFBooleanTrue, it returns true. If you pass in kCFBooleanFalse, it returns false. If you pass in anything else (a CFNumberRef, CFStringRef, or any garbage) it will always return FALSE.

THRESHE
Oct 2, 2008, 01:29 PM
When I debug cfstr variable value is "not a CFString" after the value is returned plus CFShow prints "(null)".

P.S. I know about casting types ;)

THRESHE
Oct 3, 2008, 05:30 AM
I've replaced CFLocaleGetSystem() by CFLocaleCopyCurrent() and now it works as desired though it's strange that CFLocaleGetSystem() fails...