В каком формате хранятся данные в info plist property list файле
A property list is a representation of a hierarchy of objects that can be stored in the file system and reconstituted later. Property lists give applications a lightweight and portable way to store small amounts of data. They are hierarchies of data made from specific types of objects—they are, in effect, an object graph. Property lists are easy to create programmatically and are even easier to serialize into a representation that is persistent. Applications can later read the static representation back into memory and recreate the original hierarchy of objects. Both Cocoa Foundation and Core Foundation have APIs related to property list serialization and deserialization.
Data types
Property lists consist only of certain types of data: dictionaries, arrays, strings, numbers (integer and float), dates, binary data, and Boolean values. Dictionaries and arrays are special types because they are collections; they can contain one or multiple data types, including other dictionaries and arrays. This hierarchical nesting of objects creates a graph of objects. The abstract data types have corresponding Foundation classes, Core Foundation types, and XML elements for collection objects and value objects.
Data formats
You can write property lists out in XML, JSON and binary formats. The binary format is much more compact than the XML version and thus more efficient. It is recommended for most situations. However, you can manually edit an XML property list if you ever need to. You can also edit a JSON file because it is just concatenated text and much less verbose than pure XML. Property list files have the filename extension of plist.
You should not use property lists to store large, complex graphs of objects, especially when the objects have variable mutability settings. And you cannot use property lists to store objects that are not supported by the architecture, such as model objects. For these cases, use archiving instead. Although property lists can include NSData objects, it’s best to not use data objects in property lists to hold large amounts of binary data.
XML, JSON or binary?
The property list file type can be identified using the file command on macOS:
Converting between the different plist formats can be performed using the plutil command line utility on macOS:
Info.plist
Every macOS and iOS application relies on the presence of special metadata in each application or bundle. This metadata is used in many different ways. Some of it is displayed to the user, some of it is used internally by the system to identify your application location, the icon to display, the document types it supports and many other behaviours that have an impact outside the bundle itself. Some of the metadata is used by the system frameworks to facilitate the launch of applications. The way an application provides its metadata to the system is through the use of a special file called an information property list file which is named Info.plist.
Creating an Info.plist
The simplest way to create an information property list file for as macOS application is to let Lazarus create it for you. When you use the Lazarus Project > Project Options, and click the Create application bundle option, Lazarus creates a default application bundle and an Info.plist file which you can find in the project_name.app/Contents subdirectory. The file created by Lazarus comes preconfigured with basic key value pairs that every information property list should have.
Here's an example of an Info.plist created by Lazarus for a simple macOS application:
Editing an Info.plist
To edit the contents of your Info.plist file, you can use any text editor that uses UTF-8 though it may be safer to use Xcode which understands the XML formatting of information property list files. Double-click the Info.plist filename in Finder which will automatically open the Xcode property list editor.
Note: The property list editor in Xcode displays human-readable strings (instead of the actual key name) for many keys by default. To display the actual key names as they appear in the Info.plist file, Control-click any of the keys in the editor window and enable the Show Raw Keys/Values item in the contextual menu.
To edit the value for a specify key, double-click the value in the Xcode property list editor to select it, then type a new value. Most values are specified as strings but Xcode also supports several other scalar types. You can also specify complex types such as an array or dictionary. The property list editor displays an appropriate interface for editing each type. To change the type of a given value, make sure the value is not selected and Control-click it to display its contextual menu. From the Value Type submenu, select the type you want to use for the value.
Adding keys to an Info.plist
Although the Info.plist file generated by Lazarus contains the most critical keys required by the system, most applications should typically specify several additional keys. Many subsystems and system applicationss use the Info.plist file to gather information about your application. For example, when the user chooses File > Get Info for your application, the Finder displays information from many of these keys in the resulting information window.
To add a key/value pair:
- Click the Add button (+) beside a key in the property list editor or select an existing property and press Return.
- Choose a key from the pop-up menu (press the Down Arrow key to display it if it’s not visible) or type a new key name in the Key column.
- Choose a type from the pop-up menu in the Type column.
- Enter a value in the Value column.
To add a value to an array or dictionary, expand the disclosure triangle beside the array or dictionary. Next, click the Add button (+) or press Return to add a child property.
To delete a key/value pair:
- Click the Remove button (—) beside a key in the property list editor or select a property and press Delete.
Syntax checking
In cases where you have edited a property list file by hand rather than by using Xcode's property list editor, it is prudent to syntax check the file using the plutil command line utility on macOS. This is very handy because plutil will tell you the number of the line on which it finds an error.
A successful syntax check:
An syntax check where a problem has been found:
Of course plutil will syntax check any property list file, not just Info.plist.
Recommended Key/Value pairs
An iOS application should include the following keys in its information property list file:
- CFBundleDevelopmentRegion
- CFBundleDisplayName
- CFBundleExecutable
- CFBundleIconFiles
- CFBundleIdentifier
- CFBundleInfoDictionaryVersion
- CFBundlePackageType
- CFBundleVersion
- LSRequiresIPhoneOS
In addition to these keys, there are several that are commonly included:
- UIRequiredDeviceCapabilities (required)
- UIStatusBarStyle
- UIInterfaceOrientation
- UIRequiresPersistentWiFi
macOS Cocoa
A macOS Cocoa application should include the following keys in its information property list file. Most are set by Lazarus automatically when you create your application bundle, but some will need to be edited and some may need to be added.
- CFBundleDevelopmentRegion
- CFBundleDisplayName
- CFBundleExecutable
- CFBundleIconFile
- CFBundleIdentifier
- CFBundleInfoDictionaryVersion
- CFBundleName
- CFBundlePackageType
- CFBundleShortVersionString
- CFBundleVersion
- NSHumanReadableCopyright
Localizing an Info.plist
The values for many keys in an information property list file are human-readable strings that are displayed to the user by the Finder or your own app. When you localize your app, you should be sure to localize the values for these strings in addition to the rest of your app’s content.
Localized values are not stored in the Info.plist file itself. Instead, you store the values for a particular localization in a strings file with the name InfoPlist.strings. You place this file in the same language-specific project directory that you use to store other resources for the same localization. The contents of the InfoPlist.strings file are the individual keys you want localized and the appropriately translated value. The routines that look up key values in the Info.plist file take the user’s language preferences into account and return the localized version of the key (from the appropriate InfoPlist.strings file) when one exists. If a localized version of a key does not exist, the routines return the value stored in the Info.plist file.
In addition to the recommended keys, there are several keys that should be localized and placed in your language-specific InfoPlist.strings files:
- CFBundleDisplayName
- CFBundleName
- CFBundleShortVersionString
- NSHumanReadableCopyright
For example, TextEdit has several keys that are displayed in the Finder and thus should be localized. Suppose your information property list file defines the following keys:
The French localization for TextEdit then includes the following strings in the InfoPlist.strings file of its Contents/Resources/French.lproj directory:
Protected Resources
With the introduction of macOS 10.15 (Catalina), users have to consent for an application to use:
- Camera
- Microphone
- Screen recording
- Keyboard input monitoring (except for the applications own input)
- Files and folders protection:
- Data that requires user consent to access
- Private data which is managed by the system.
New protected areas in Catalina:
- Desktop
- Documents
- Downloads
- iCloud Drive
- Third-party cloud storage (Dropbox, OneDrive, Box, etc.)
- Removable volumes
- Network volumes
User consent is not required to create new files in protected locations. Only reading data from protected locations. Files can be checked to see if they're readable/writable without triggering consent dialogs.
Private data managed by the system:
An application does not need Full Disk Access to move a file to the Trash, but needs authorization to the file being moved. The caller retains access to the file, even once it's in the Trash.
When an application attempts to access, for example, a user's Documents folder, a default dialog will be displayed asking the user for permission.
A sample of the generic dialog from macOS 11.2.3 (Big Sur) which asks for user consent is on the left.
The user is shown with this dialog only the first time that the application is run. Note that if a developer rebuilds the application, and it is not signed, then the dialog will be shown again.
To enable a developer to show a more helpful consent dialog which explains why access is required to the protected resource, a number of new property list keys are available:
To provide a better experience for users, iOS and macOS rely on the presence of special metadata in each app or bundle. This metadata is used in many different ways. Some of it is displayed to the user, some of it is used internally by the system to identify your app and the document types it supports, and some of it is used by the system frameworks to facilitate the launch of apps. The way an app provides its metadata to the system is through the use of a special file called an information property list file, or Info.plist for short.
A property list is a way to structure arbitrary data that the system can access at runtime. An information property list is a specialized type of property list that contains configuration data for a bundle. The keys and values in the file describe the various behaviors and configuration options you want applied to your bundle. An Xcode project template typically specifies an information property list file with an initial set of keys and appropriate default values. You can edit the file to change or add keys and values, as appropriate for your project.
At a Glance
This document describes the keys and corresponding values that you can include in an information property list file. This document also includes an overview of information property list files to help you understand their importance and to provide tips on how to configure them.
The Info.plist File Configures Your App
Every app and plug-in uses an Info.plist file to store configuration data in a place where the system can easily access it. macOS and iOS use Info.plist files to determine what icon to display for a bundle, what document types an app supports, and many other behaviors that have an impact outside the bundle itself.
Core Foundation Keys Describe Common Behavior
There are many keys that you always specify, regardless of the type of bundle you are creating. Those keys start with a CF prefix and are known as the Core Foundation keys. Xcode includes the most important keys in your Info.plist automatically but there are others you must add manually.
Relevant chapter: Core Foundation Keys
Launch Services Keys Describe Launch-Time Behavior
Launch Services provides support for launching apps. To do this, though, it needs to know information about how your app wants to be launched. The Launch Services keys describe the way your app prefers to be launched.
Relevant chapter: Launch Services Keys
Cocoa Keys Describe Behavior for Cocoa and Cocoa Touch Apps
The Cocoa and Cocoa Touch frameworks use keys to identify high-level information such as your app’s main nib file and principal class. The Cocoa keys describe those and other keys that affect how the Cocoa and Cocoa Touch frameworks initialize and run your app.
Relevant chapter: Cocoa Keys
macOS Keys Describe Behavior for macOS Apps
Some macOS frameworks use keys to modify their basic behavior. Developers of Mac apps might include these keys during testing or to modify certain aspects of your app’s behavior.
Relevant chapter: macOS Keys
iOS Keys Describe Behavior for iOS Apps
An iOS app communicates a lot of information to the system using Info.plist keys. Xcode supplies a standard Info.plist with the most important keys but most apps need to augment the standard file with additional keys describing everything from the app’s initial orientation to whether it supports file sharing.
Relevant chapter: iOS Keys
watchOS Keys Describe Behavior for Watch Apps
Use the Info.plist keys associated with the watchOS frameworks to configure your Watch apps and WatchKit extensions.
Relevant chapter: watchOS Keys
App Extension Keys Describe Behavior for iOS and macOS App Extensions
App extensions let you make custom behaviors available in other apps and in system facilities such as notification center. Xcode’s app extension templates each supply a standard Info.plist file with the most important keys, but you can specify additional keys that describe custom behavior for your app extensions.
Relevant chapter: App Extension Keys
See Also
For an introduction to property lists, including how they are structured and how you use them in general, see Property List Programming Guide.
Some Info.plist keys use Uniform Type Identifiers (UTIs) to refer to data of different types. For an introduction to UTIs and how they are specified, see Uniform Type Identifiers Overview.
Kernel extension developers need to use certain Info.plist keys in different ways than app developers do, and also need some kernel-extension-specific keys that have no use in app development. If you are developing a kernel extension, refer to the chapter Info.plist Properties for Kernel Extensions in Kernel Extension Programming Topics.
An information property list file is a structured text file that contains essential configuration information for a bundled executable. The file itself is typically encoded using the Unicode UTF-8 encoding and the contents are structured using XML. The root XML node is a dictionary, whose contents are a set of keys and values describing different aspects of the bundle. The system uses these keys and values to obtain information about your app and how it is configured. As a result, all bundled executables (plug-ins, frameworks, and apps) are expected to have an information property list file.
By convention, the name of an information property list file is Info.plist . This name of this file is case sensitive and must have an initial capital letter I . In iOS apps, this file resides in the top-level of the bundle directory. In macOS bundles, this file resides in the bundle’s Contents directory. Xcode typically creates this file for you automatically when you create a project of an appropriate type.
Important: In the sections that follow, pay attention to the capitalization of files and directories that reside inside a bundle. The NSBundle class and Core Foundation bundle functions consider case when searching for resources inside a bundle directory. Case mismatches could prevent you from finding your resources at runtime.
Creating and Editing an Information Property List File
The simplest way to create an information property list file is to let Xcode create it for you. Each new bundle-based project that you create in Xcode comes with a file named -Info.plist , where is the name of the project. At build time, this file is used to generate the Info.plist file that is then included in the resulting bundle.
To edit the contents of your information property list file, select the -Info.plist file in your Xcode project to display the property list editor. Figure 1 shows the editor for the information property list file of a new Cocoa app project. The file created by Xcode comes preconfigured with keys that every information property list should have.
Figure 1 Editing the information property list in Xcode
To edit the value for a specify key, double-click the value in the Xcode property list editor to select it, then type a new value. Most values are specified as strings but Xcode also supports several other scalar types. You can also specify complex types such as an array or dictionary. The property list editor displays an appropriate interface for editing each type. To change the type of a given value, make sure the value is not selected and Control-click it to display its contextual menu. From the Value Type submenu, select the type you want to use for the value.
Because information property lists are usually just text files, you can also edit them using any text editor that supports the UTF-8 file encoding. Because they are XML files, however, editing property list files manually is generally discouraged.
Adding Keys to an Information Property List File
Although the Info.plist file provided by Xcode contains the most critical keys required by the system, most apps should typically specify several additional keys. Many subsystems and system apps use the Info.plist file to gather information about your app. For example, when the user chooses File > Get Info for your app, the Finder displays information from many of these keys in the resulting information window.
You add keys to your app’s Info.plist using the Xcode property list editor. For information about how to use this editor, see “ Edit property lists .”
Important: The property list editor in Xcode displays human-readable strings (instead of the actual key name) for many keys by default. To display the actual key names as they appear in the Info.plist file, Control-click any of the keys in the editor window and enable the Show Raw Keys/Values item in the contextual menu.
For a list of the recommended keys you should include in a typical app, see Recommended Info.plist Keys .
Localizing Property List Values
The values for many keys in an information property list file are human-readable strings that are displayed to the user by the Finder or your own app. When you localize your app, you should be sure to localize the values for these strings in addition to the rest of your app’s content.
Localized values are not stored in the Info.plist file itself. Instead, you store the values for a particular localization in a strings file with the name InfoPlist.strings . You place this file in the same language-specific project directory that you use to store other resources for the same localization. The contents of the InfoPlist.strings file are the individual keys you want localized and the appropriately translated value. The routines that look up key values in the Info.plist file take the user’s language preferences into account and return the localized version of the key (from the appropriate InfoPlist.strings file) when one exists. If a localized version of a key does not exist, the routines return the value stored in the Info.plist file.
For example, the TextEdit app has several keys that are displayed in the Finder and thus should be localized. Suppose your information property list file defines the following keys:
The French localization for TextEdit then includes the following strings in the InfoPlist.strings file of its Contents/Resources/French.lproj directory:
For more information about the placement of InfoPlist.strings files in your bundle, see Bundle Programming Guide. For information about creating strings files, see Resource Programming Guide. For additional information about the localization process, see Internationalization and Localization Guide.
Creating Platform- and Device-Specific Keys
You can designate a key in an Info.plist file as applying to a specific platform, a specific device type, or both. To create a platform- or device-specific key variant, combine a root key name with one or two qualifiers, using the following pattern:
In this pattern, the key_root portion represents the original name of the key, as you find it in this document. The and portions are optional and restrict the key’s applicability to a specific platform or device type. Notice that if you employ a platform qualifier, connect it with a hyphen ( - ), and if you employ a device qualifier, connect it with a tilde ( ~ ).
Use of a device qualifier is much more common than is use of a platform qualifier.
For a device qualifier, you can use one of the following values:
iphone The key applies to iPhone devices only
ipod The key applies to iPod touch devices only
ipad The key applies to iPad devices only
For a platform qualifier, you can specify a value of iphoneos or macos depending on which of these two platforms you are targeting.
When specifying a key variant, do so in addition to employing a corresponding key without any qualifiers, thereby ensuring you provide a reasonable default value. When the system searches for a key in your app’s Info.plist file, it chooses the key that is most specific to the current device and platform. If it does not find a qualified key, it looks for one without qualifiers. For example, to specify support for all device orientations on iPad, and three orientations for iPhone, the Xcode templates specify the corresponding keys in an app’s Info.plist file:
Custom Keys
iOS and macOS ignore custom keys you include in an Info.plist file. If you want to include app-specific configuration information in your Info.plist file, you can do so freely as long as your key names do not conflict with the ones Apple uses. When defining custom key names, prefix them with a unique prefix, such as your app’s bundle ID or your company’s domain name, to prevent conflicts.
Recommended Info.plist Keys
Each of the Xcode application templates includes an Info.plist file, but you can also construct one from scratch. When creating an information property list file, there are several keys you should always include. These keys are almost always accessed by the system and providing them ensures that the system has the information it needs to work with your app effectively.
Recommended Keys for iOS Apps
It is recommended that an iOS app include the following keys in its information property list file. Most are set by Xcode automatically when you create your project.
Сегодня я бы хотел рассказать о некоторых аспектах сохранения настроек и прочих данных программы в OS X и/или iOS. Как обычно, у нас есть несколько вариантов: Core Data, «голый» SQLite, свои бинарные форматы, свои текстовые форматы, NSUserDefaults и, как Вы уже наверняка слышали, файлы типа PLIST, то есть XML Property List.
Вкратце, plist-файлы представляют из себя обычный XML, но с некоторыми оговорками. К примеру, порядок тегов в нём обусловлен некоторыми правилами: они идут парами «ключ-значение», но теги типа «ключ» и теги типа «значение» располагаются на одном уровне. Типичный пример:
Плисты умеют хранить основные типы данных Cocoa: NSString, NSNumber (int, float, BOOL), NSDate, NSArray, NSDictionary и NSData. Этим типам соответствуют следующие теги: , , , , , , , , . Собственно, plist состоит из тегов , за которыми следуют перечисленные теги со значением.Под катом - описание дополнительных ограничений и, что самое главное, API для работы с такими файлами.
Наверняка Вы уже обратили внимание на возможность хранить в plist'е массивы и словари и у Вас возникли закономерные вопросы: "а как это?", "а если в массиве мои объекты?", "а если в словаре ещё словари?" и подобные им. Если не возникло, значит эту часть статьи можно пропустить без ущерба для понимания.Дело в том, что массивы и словари при сериализации в плист проходятся рекурсивно, то есть, получается всего лишь ещё один уровень вложенности на каждый массив или словарь внутри другого контейнера. Отсюда и вытекают ограничения на содержимое: только типы, поддающиеся сериализации. То есть, массив вьюшек Вы таким способом не сериализуете, даже не пытайтесь. Но многие свои типы можете: достаточно имплементировать протокол NSCoding и получить NSData из своего объекта с помощью NSKeyedArchiver. А уж NSData и в плисте сохранить легко. Опробовать такой метод сериализации и десериализации своих объектов я оставляю Вам в качестве домашнего задания.
Ещё один интересный момент. Для ускорения чтения и записи плисты часто делают двоичными, переводят в формат bplist (Binary Plist), что снижает их удобочитаемость практически до нуля. Но не расстраиваемся: Xcode умеет открывать и такие плисты, но если Вы хотите всё ж посмотреть на XML в другом редакторе, Вы можете легко переконвертировать бинарный плист в текстовый из консоли: plutil -convert xml1 MyFile.plist . Кстати, plutil умеет конвертировать плист ещё и в JSON, это может кому-либо пригодиться, но лично я этим ни разу не пользовался.
Очень часто с плистами разработчик работает посредством NSUserDefaults, пусть даже он об этом зачастую и не знает. Этот класс разработан для работы с глобальными настройками программы, хранимыми в ~/Library/Preferences/com.yourcompany.yourapp.plist (который, кстати, обычно бинарный, то есть, bplist), и переключить его на работу с другим файлом нельзя. Но ведь мы хотим создавать и читать свои собственные плисты, не так ли? Для этого мы будем использовать простой класс NSPropertyListSerialization , заботливо предоставленный нам разработчиками Cocoa.
Итак, что же умеет этот класс? Для начала, он умеет преобразовывать NSDictionary и NSArray в NSData, содержащий наш plist. И, разумеется, он умеет делать обратные преобразования: из NSData в NSDictionary или NSArray.
Рассмотрим простой пример: создадим словарик с кучей данных (в том числе вложенных) и посмотрим на практике, во что это дело сохранится.
В результате выполнения этого кода, который слишком простой, что бы его ещё и комментировать, будет плист примерно такого вида:
Что, просто? Конечно просто! И даже XML достаточно удобочитаемый. А в консоль ещё и свалится текстовое описание нашего словарика:Теперь будем загружать сохранённый на этом этапе плист:
И что же мы должны получить? Ну конечно же! Мы в консоли должны увидеть тот же симпатичный JSON-чик, что и при сохранении! Правда, нет гарантий, что он будет именно таким же: порядок следования элементов в NSDictionary не определён. Но все данные должны быть на месте.Кстати говоря, мы загрузили наши данные в виде "mutable" данных, на что указывает флаг NSPropertyListMutableContainersAndLeaves . Если бы мы указали NSPropertyListImmutable , то получили бы не NSMutableDictionary, а обычный NSDictionary, так что тут есть небольшой простор для фантазии и оптимизации.
Что ж, в этом уроке мы немного разобрались с форматом PLIST и научились работать с файлами такого типа с помощью Cocoa. Полный пример можно найти, как всегда, на гитхабе.
UPD: Как заметил mejedi, бинарный формат плиста иногда может записываться в файл медленней plain-XML формата.
XML пишется «в лоб», а при сохранении в бинарный формат происходит поиск и устранение дублирующих элементов (формат по сути представляет собой поток сущностей с взаимными ссылками, например если у нас два раза строка «hello world» встречается, хранить две копии не обязательно).
Сейчас посмотрел код, чтобы освежить память — на 10.6 все так, как я описал, а на 10.8 устранение дубликатов больше не делается, по-идее должно стать быстрее (релевантная функция называется __CFBinaryPlistWrite).
A property list is a representation of a hierarchy of objects that can be stored in the file system and reconstituted later. Property lists give applications a lightweight and portable way to store small amounts of data. They are hierarchies of data made from specific types of objects—they are, in effect, an object graph. Property lists are easy to create programmatically and are even easier to serialize into a representation that is persistent. Applications can later read the static representation back into memory and recreate the original hierarchy of objects. Both Cocoa Foundation and Core Foundation have APIs related to property list serialization and deserialization.
Data types
Property lists consist only of certain types of data: dictionaries, arrays, strings, numbers (integer and float), dates, binary data, and Boolean values. Dictionaries and arrays are special types because they are collections; they can contain one or multiple data types, including other dictionaries and arrays. This hierarchical nesting of objects creates a graph of objects. The abstract data types have corresponding Foundation classes, Core Foundation types, and XML elements for collection objects and value objects.
Data formats
You can write property lists out in XML, JSON and binary formats. The binary format is much more compact than the XML version and thus more efficient. It is recommended for most situations. However, you can manually edit an XML property list if you ever need to. You can also edit a JSON file because it is just concatenated text and much less verbose than pure XML. Property list files have the filename extension of plist.
You should not use property lists to store large, complex graphs of objects, especially when the objects have variable mutability settings. And you cannot use property lists to store objects that are not supported by the architecture, such as model objects. For these cases, use archiving instead. Although property lists can include NSData objects, it’s best to not use data objects in property lists to hold large amounts of binary data.
XML, JSON or binary?
The property list file type can be identified using the file command on macOS:
Converting between the different plist formats can be performed using the plutil command line utility on macOS:
Info.plist
Every macOS and iOS application relies on the presence of special metadata in each application or bundle. This metadata is used in many different ways. Some of it is displayed to the user, some of it is used internally by the system to identify your application location, the icon to display, the document types it supports and many other behaviours that have an impact outside the bundle itself. Some of the metadata is used by the system frameworks to facilitate the launch of applications. The way an application provides its metadata to the system is through the use of a special file called an information property list file which is named Info.plist.
Creating an Info.plist
The simplest way to create an information property list file for as macOS application is to let Lazarus create it for you. When you use the Lazarus Project > Project Options, and click the Create application bundle option, Lazarus creates a default application bundle and an Info.plist file which you can find in the project_name.app/Contents subdirectory. The file created by Lazarus comes preconfigured with basic key value pairs that every information property list should have.
Here's an example of an Info.plist created by Lazarus for a simple macOS application:
Editing an Info.plist
To edit the contents of your Info.plist file, you can use any text editor that uses UTF-8 though it may be safer to use Xcode which understands the XML formatting of information property list files. Double-click the Info.plist filename in Finder which will automatically open the Xcode property list editor.
Note: The property list editor in Xcode displays human-readable strings (instead of the actual key name) for many keys by default. To display the actual key names as they appear in the Info.plist file, Control-click any of the keys in the editor window and enable the Show Raw Keys/Values item in the contextual menu.
To edit the value for a specify key, double-click the value in the Xcode property list editor to select it, then type a new value. Most values are specified as strings but Xcode also supports several other scalar types. You can also specify complex types such as an array or dictionary. The property list editor displays an appropriate interface for editing each type. To change the type of a given value, make sure the value is not selected and Control-click it to display its contextual menu. From the Value Type submenu, select the type you want to use for the value.
Adding keys to an Info.plist
Although the Info.plist file generated by Lazarus contains the most critical keys required by the system, most applications should typically specify several additional keys. Many subsystems and system applicationss use the Info.plist file to gather information about your application. For example, when the user chooses File > Get Info for your application, the Finder displays information from many of these keys in the resulting information window.
To add a key/value pair:
- Click the Add button (+) beside a key in the property list editor or select an existing property and press Return.
- Choose a key from the pop-up menu (press the Down Arrow key to display it if it’s not visible) or type a new key name in the Key column.
- Choose a type from the pop-up menu in the Type column.
- Enter a value in the Value column.
To add a value to an array or dictionary, expand the disclosure triangle beside the array or dictionary. Next, click the Add button (+) or press Return to add a child property.
To delete a key/value pair:
- Click the Remove button (—) beside a key in the property list editor or select a property and press Delete.
Syntax checking
In cases where you have edited a property list file by hand rather than by using Xcode's property list editor, it is prudent to syntax check the file using the plutil command line utility on macOS. This is very handy because plutil will tell you the number of the line on which it finds an error.
A successful syntax check:
An syntax check where a problem has been found:
Of course plutil will syntax check any property list file, not just Info.plist.
Recommended Key/Value pairs
An iOS application should include the following keys in its information property list file:
- CFBundleDevelopmentRegion
- CFBundleDisplayName
- CFBundleExecutable
- CFBundleIconFiles
- CFBundleIdentifier
- CFBundleInfoDictionaryVersion
- CFBundlePackageType
- CFBundleVersion
- LSRequiresIPhoneOS
In addition to these keys, there are several that are commonly included:
- UIRequiredDeviceCapabilities (required)
- UIStatusBarStyle
- UIInterfaceOrientation
- UIRequiresPersistentWiFi
macOS Cocoa
A macOS Cocoa application should include the following keys in its information property list file. Most are set by Lazarus automatically when you create your application bundle, but some will need to be edited and some may need to be added.
- CFBundleDevelopmentRegion
- CFBundleDisplayName
- CFBundleExecutable
- CFBundleIconFile
- CFBundleIdentifier
- CFBundleInfoDictionaryVersion
- CFBundleName
- CFBundlePackageType
- CFBundleShortVersionString
- CFBundleVersion
- NSHumanReadableCopyright
Localizing an Info.plist
The values for many keys in an information property list file are human-readable strings that are displayed to the user by the Finder or your own app. When you localize your app, you should be sure to localize the values for these strings in addition to the rest of your app’s content.
Localized values are not stored in the Info.plist file itself. Instead, you store the values for a particular localization in a strings file with the name InfoPlist.strings. You place this file in the same language-specific project directory that you use to store other resources for the same localization. The contents of the InfoPlist.strings file are the individual keys you want localized and the appropriately translated value. The routines that look up key values in the Info.plist file take the user’s language preferences into account and return the localized version of the key (from the appropriate InfoPlist.strings file) when one exists. If a localized version of a key does not exist, the routines return the value stored in the Info.plist file.
In addition to the recommended keys, there are several keys that should be localized and placed in your language-specific InfoPlist.strings files:
- CFBundleDisplayName
- CFBundleName
- CFBundleShortVersionString
- NSHumanReadableCopyright
For example, TextEdit has several keys that are displayed in the Finder and thus should be localized. Suppose your information property list file defines the following keys:
The French localization for TextEdit then includes the following strings in the InfoPlist.strings file of its Contents/Resources/French.lproj directory:
Protected Resources
With the introduction of macOS 10.15 (Catalina), users have to consent for an application to use:
- Camera
- Microphone
- Screen recording
- Keyboard input monitoring (except for the applications own input)
- Files and folders protection:
- Data that requires user consent to access
- Private data which is managed by the system.
New protected areas in Catalina:
- Desktop
- Documents
- Downloads
- iCloud Drive
- Third-party cloud storage (Dropbox, OneDrive, Box, etc.)
- Removable volumes
- Network volumes
User consent is not required to create new files in protected locations. Only reading data from protected locations. Files can be checked to see if they're readable/writable without triggering consent dialogs.
Private data managed by the system:
An application does not need Full Disk Access to move a file to the Trash, but needs authorization to the file being moved. The caller retains access to the file, even once it's in the Trash.
When an application attempts to access, for example, a user's Documents folder, a default dialog will be displayed asking the user for permission.
A sample of the generic dialog from macOS 11.2.3 (Big Sur) which asks for user consent is on the left.
The user is shown with this dialog only the first time that the application is run. Note that if a developer rebuilds the application, and it is not signed, then the dialog will be shown again.
To enable a developer to show a more helpful consent dialog which explains why access is required to the protected resource, a number of new property list keys are available:
Читайте также: