|
Май
27
|
Локаль (англ. — Locale) — это не язык, а набор параметров, способ представления данных, включая валюту, дробный разделитель, единицы измерения, формат числа и даты. Идентификатор локаля представлен как “languagecode_regioncode_variant”. Преобразование присваиваемых имен регулируется нормами ICU (International Components for Unicode). В этом варианте нет необходимости для английского языка в США (идентификатор локаля “en_US”) и в Великобритании (”en_GB”). Для настройки локаля в iPhone выполните “Settings -> General -> International -> Region Format“. В этом уроке мы рассмотрим отображение данных (валюта, дата, время) для указанного пользователем региона (страны).
Форматеры.
Как правило, операции выполняются не с конкретным локалем, а с текущим пользовательским объектом. Объект локаля функционирует в комплексе с другими объектами — форматерами. В Cocca это “NSNumberFormatter” и “NSDateFormatter“. Эти классы чувствительны к локалю: при создании экземпляра используется текущий локаль пользователя, что весьма упрощает работу. Для доступа к локалю пользователя и созданию новых объектов используется класс “NSLocale“.
Код для получения текущего локаля выглядит примерно так:
1 2 3 4 5 | NSLocale *currentUsersLocale = [NSLocale currentLocale]; NSLog(@"Current Locale: %@", [currentUsersLocale localeIdentifier]); //Выходные данные Current Locale: en_US |
Чтобы получить текущий локаль, передаем классу сообщение “currentLocale” и получаем идентификатор (представление строки) передачей сообщения “localeIdentifier“. Если в настройках региона указаны США, результатом будет “en_US“.
Работа с “NSNumberFormatter”.
Сам код крайне прост, а изучение форматеров не отнимет много времени. Создаем новые, настраиваем свойства, применяем с классом “NSNumber“. Ниже приведен код с числами и различными форматерами (итоговый результат выводится на консоль отладчика).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | //Получаем текущий локаль пользователя. NSLocale *currentLocale = [NSLocale currentLocale]; NSLog(@"Current Locale: %@", [currentLocale localeIdentifier]); NSLog(@"Test numbers: 4.0, 0.4, 4.6, -64"); NSNumber *number40 = [NSNumber numberWithFloat:4.0]; NSNumber *number04 = [NSNumber numberWithFloat:0.4]; NSNumber *number46 = [NSNumber numberWithFloat:4.6]; NSNumber *number64 = [NSNumber numberWithInt:-64]; //Работаем с числом 4.0, представляя как "No Style" NSNumberFormatter *noStyleFormatter = [[NSNumberFormatter alloc] init]; [noStyleFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [noStyleFormatter setNumberStyle:NSNumberFormatterNoStyle]; //Десятичный стиль NSNumberFormatter *decimalStyle = [[NSNumberFormatter alloc] init]; [decimalStyle setFormatterBehavior:NSNumberFormatterBehavior10_4]; [decimalStyle setNumberStyle:NSNumberFormatterDecimalStyle]; [decimalStyle setRoundingMode:NSNumberFormatterRoundFloor]; [decimalStyle setRoundingIncrement:[NSNumber numberWithInt:1]]; //Стиль валюты NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init]; [currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4]; [currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle]; //Стиль процентов NSNumberFormatter *percentStyle = [[NSNumberFormatter alloc] init]; [percentStyle setFormatterBehavior:NSNumberFormatterBehavior10_4]; [percentStyle setNumberStyle:NSNumberFormatterPercentStyle]; //Научный стиль NSNumberFormatter *scientificStyle = [[NSNumberFormatter alloc] init]; [scientificStyle setFormatterBehavior:NSNumberFormatterBehavior10_4]; [scientificStyle setNumberStyle:NSNumberFormatterScientificStyle]; //Стиль спелинга NSNumberFormatter *spellOutStyle = [[NSNumberFormatter alloc] init]; [spellOutStyle setFormatterBehavior:NSNumberFormatterBehavior10_4]; [spellOutStyle setNumberStyle:NSNumberFormatterSpellOutStyle]; NSLog(@"Locale of noStyle formatter: %@", [[noStyleFormatter locale] localeIdentifier]); NSLog(@"Locale of decimal style formatter: %@", [[decimalStyle locale] localeIdentifier]); NSLog(@"Locale of currency style formatter: %@", [[currencyStyle locale] localeIdentifier]); NSLog(@"Locale of percent style formatter: %@", [[percentStyle locale] localeIdentifier]); NSLog(@"Locale of scientific style formatter: %@", [[scientificStyle locale] localeIdentifier]); NSLog(@"Locale of spell-out style formatter: %@", [[spellOutStyle locale] localeIdentifier]); NSLog(@"---------------------------------------"); //Отображение результатов NSLog(@"Different formatting results for NSNumber 4.0 with Locale: %@", [currentLocale localeIdentifier]); NSLog(@"---------------------------------------"); NSLog(@"Formatting 4.0 with No Style: %@", [noStyleFormatter stringFromNumber:number40]); NSLog(@"Formatting 4.0 with Decimal Style: %@", [decimalStyle stringFromNumber:number40]); NSLog(@"Formatting 4.0 with Currency Style: %@", [currencyStyle stringFromNumber:number40]); NSLog(@"Formatting 4.0 with Percent Style: %@", [percentStyle stringFromNumber:number40]); NSLog(@"Formatting 4.0 with Scientific Style: %@", [scientificStyle stringFromNumber:number40]); NSLog(@"Formatting 4.0 with Spell Out Style: %@", [spellOutStyle stringFromNumber:number40]); NSLog(@"---------------------------------------"); NSLog(@"Different formatting results for NSNumber 0.4 with Locale: %@", [currentLocale localeIdentifier]); NSLog(@"---------------------------------------"); NSLog(@"Formatting with No Style: %@", [noStyleFormatter stringFromNumber:number04]); NSLog(@"Formatting with Decimal Style: %@", [decimalStyle stringFromNumber:number04]); NSLog(@"Formatting with Currency Style: %@", [currencyStyle stringFromNumber:number04]); NSLog(@"Formatting with Percent Style: %@", [percentStyle stringFromNumber:number04]); NSLog(@"Formatting with Scientific Style: %@", [scientificStyle stringFromNumber:number04]); NSLog(@"Formatting with Spell Out Style: %@", [spellOutStyle stringFromNumber:number04]); NSLog(@"---------------------------------------"); NSLog(@"Different formatting results for NSNumber 4.6 with Locale: %@", [currentLocale localeIdentifier]); NSLog(@"---------------------------------------"); NSLog(@"Formatting with No Style: %@", [noStyleFormatter stringFromNumber:number46]); NSLog(@"Formatting with Decimal Style: %@", [decimalStyle stringFromNumber:number46]); NSLog(@"Formatting with Currency Style: %@", [currencyStyle stringFromNumber:number46]); NSLog(@"Formatting with Percent Style: %@", [percentStyle stringFromNumber:number46]); NSLog(@"Formatting with Scientific Style: %@", [scientificStyle stringFromNumber:number46]); NSLog(@"Formatting with Spell Out Style: %@", [spellOutStyle stringFromNumber:number46]); NSLog(@"---------------------------------------"); NSLog(@"Different formatting results for NSNumber -64 with Locale: %@", [currentLocale localeIdentifier]); NSLog(@"---------------------------------------"); NSLog(@"Formatting with No Style: %@", [noStyleFormatter stringFromNumber:number64]); NSLog(@"Formatting with Decimal Style: %@", [decimalStyle stringFromNumber:number64]); NSLog(@"Formatting with Currency Style: %@", [currencyStyle stringFromNumber:number64]); NSLog(@"Formatting with Percent Style: %@", [percentStyle stringFromNumber:number64]); NSLog(@"Formatting with Scientific Style: %@", [scientificStyle stringFromNumber:number64]); NSLog(@"Formatting with Spell Out Style: %@", [spellOutStyle stringFromNumber:number64]); NSLog(@"---------------------------------------"); |
Данный код всего лишь создает группу форматеров на основе различных стилей и демонстрирует представление данных. Поведение форматеров настраивается на “NSNumberFormatterBehavior10_4” (Mac OS X 10.4). Для вывода числа передаем форматеру сообщение “stringFromNumber“. С помощью “NSNumberFormatter” настраиваются символ валюты, положительные/отрицательные значения, меняются многие настройки по умолчанию. Подробный список всех доступных методов и свойств можно получить [здесь].
Работа с “NSDateFormatter”.
Как и предыдущий форматер, “NSDateFormatter” чувствителен к локалю. Приведенный ниже код показывает пример его использования:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //Форматеры даты. [NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterLongStyle]; [dateFormatter setTimeStyle:NSDateFormatterNoStyle]; NSDate *date = [NSDate date]; NSString *formattedDateString = [dateFormatter stringFromDate:date]; NSLog(@"Formatted date string for locale %@: %@", [[dateFormatter locale] localeIdentifier], formattedDateString); //Пользователький форматер даты. NSDateFormatter *customDateFormatter = [[NSDateFormatter alloc] init]; //При настройке формата даты не указывайте сразу стили даты и времени. //Настраивать можно только один стиль, иначе второй просто его скопирует. [customDateFormatter setDateFormat:@"'The time is' hh:mm 'on' EEEE MMMM d"]; NSLog(@"%@", [customDateFormatter stringFromDate:date]); |
С помощью “NSDateFormatter” можно указывать обозначения месяцев, настраивать временной пояс, задавать символы отображения времени AM/PM. Подробный список всех доступных методов и свойств можно получить [здесь].
Заключение.
Всегда прибегайте к форматеру при отображении валют, единиц измерения, формата даты/времени, чтобы он присутствовал в пользовательском локале. Надеюсь, несмотря на простоту темы и кода, статья оказалась полезной. Удачи!


Март 14th, 2010 at 10:19
iPhone Application writes data to a text file, saves it on the Documnets folder. Great that works
If I place “£” in the string, or use [currencyStyle stringFromNumber] the text file will not be created.
The “£” and the [currencyStyle stringFromNumber] works if the information is printed to a “New View” page on the simulator, pound and all
Can someone please explain what’s happening?