Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does [NSLocale preferredLanguages] return empty?

Tags:

ios

iphone

Is there any possibility that [NSLocale preferredLanguages] be empty?

I get the preferredLanguages like:

NSString* preLang = [[NSLocale preferredLanguages] objectAtIndex:0] in a class method.

But sometimes (not always) the app will crash at this line.

I have called [NSLocale preferredLanguages] many times in my app. Some are in instance methods and TWO are in class methods.

And both of the two in the class methods are crashing randomly.

What's the problem?

Here is the crash log:

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x00000000000007d8
Triggered by Thread:  0

Thread 0 Crashed:
0   libobjc.A.dylib                 0x399c0911 realizeClass(objc_class*) + 21
1   libobjc.A.dylib                 0x399c09d7 realizeClass(objc_class*) + 219
2   libobjc.A.dylib                 0x399c2793 lookUpImpOrForward + 71
3   libobjc.A.dylib                 0x399bb027 _class_lookupMethodAndLoadCache3 + 31
4   libobjc.A.dylib                 0x399badf7 _objc_msgSend_uncached + 23
5   CoreFoundation                  0x2f58f607 CFArrayAppendValue + 127
6   CoreFoundation                  0x2f5dc477 CFLocaleCopyPreferredLanguages + 155
7   CoreFoundation                  0x2f5e417d +[NSLocale preferredLanguages] + 5

Thanks

like image 401
Ecroo Avatar asked Mar 19 '14 15:03

Ecroo


1 Answers

The problem is not it returning nil but returning an empty array. Because NSArray throws an exception for out of bounds access (instead of nil like it should) you get a crash.

This will return nil instead of crashing.

Replace

[[NSLocale preferredLanguages] objectAtIndex:0]

With

[[NSLocale preferredLanguages] firstObject]

If -preferredLanguages returns and empty array then -firstObject will return nil instead of throwing an exception like -objectAtIndex:.

like image 106
Kyle Howells Avatar answered Sep 18 '22 06:09

Kyle Howells