Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CFStringTokenizerCopyBestStringLanguage with NULL Range

I'm trying to use CFStringTokenizerCopyBestStringLanguage. The docs say:

The range of string to use for the test. If NULL, the first few hundred characters of the string are examined.

But passing NULL yields an error:

Passing 'void *' to parameter of incompatible type 'CFRange'

What is the correct way of doing this?

NSString *language = (NSString *)CFBridgingRelease(CFStringTokenizerCopyBestStringLanguage((CFStringRef)text, NULL));

like image 299
keegan3d Avatar asked Mar 25 '26 14:03

keegan3d


1 Answers

It looks like an error in the documentation.

NULL is typically defined as something like

#define NULL ((void*)0)

so it's a pointer.

On the other hand CFRange is defined as

struct CFRange {
   CFIndex location;
   CFIndex length;
};
typedef struct CFRange CFRange;

so it's a struct, i.e. a non-pointer type.

A struct cannot be assigned to NULL, since they have incompatible types, therefore technically speaking a CFRange cannot be NULL.

Back to your specific problem, you may want to do something like

CFStringRef text = //your text
CFRange range = CFRangeMake(0, MIN(400, CFStringGetLength(text)));
NSString *language = (NSString *)CFBridgingRelease(CFStringTokenizerCopyBestStringLanguage(text, range));

I picked 400 since the documentation states

Typically, the function requires 200-400 characters to reliably guess the language of a string.


UPDATE

I reported the error to Apple.

like image 178
Gabriele Petronella Avatar answered Mar 27 '26 12:03

Gabriele Petronella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!