Ilias Karim
Ilias Karim

Reputation: 5371

What is `NSLocalizedFailureErrorKey` for?

Among the well-documented strings NSLocalizedDescriptionKey, NSLocalizedFailureReasonErrorKey, NSLocalizedRecoveryOptionsErrorKey, and NSLocalizedRecoverySuggestionErrorKey there is also NSLocalizedFailureErrorKey, which lacks any kind of description in documentation. What is it for?

Upvotes: 1

Views: 619

Answers (2)

Mecki
Mecki

Reputation: 132869

Let me quote the documentation of -localizedDescription from NSError.h (I only applied some layouting and styling to it):

The primary user-presentable message for the error, for instance for NSFileReadNoPermissionError:

The file "File Name" couldn't be opened
because you don't have permission to view it.

This message should ideally indicate what failed and why it failed.

This value either comes from

  • NSLocalizedDescriptionKey, or
  • NSLocalizedFailureErrorKey + NSLocalizedFailureReasonErrorKey, or
  • NSLocalizedFailureErrorKey.

The steps this takes to construct the description include:

  1. Look for NSLocalizedDescriptionKey in userInfo, use value as-is if present.

  2. Look for NSLocalizedFailureErrorKey in userInfo. If present, use, combining with value for NSLocalizedFailureReasonErrorKey if available.

  3. Fetch NSLocalizedDescriptionKey from userInfoValueProvider, use value as-is if present.

  4. Fetch NSLocalizedFailureErrorKey from userInfoValueProvider. If present, use, combining with value for NSLocalizedFailureReasonErrorKey if available.

  5. Look for NSLocalizedFailureReasonErrorKey in userInfo or from userInfoValueProvider; combine with generic "Operation failed" message.

  6. Last resort localized but barely-presentable string manufactured from domain and code. The result is never nil.

Upvotes: 0

matt
matt

Reputation: 534885

From the header:

FOUNDATION_EXPORT NSErrorUserInfoKey const NSLocalizedFailureErrorKey API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));
// NSString

A complete sentence (or more) describing what failed. Setting a value for this key in userInfo dictionary of errors received from framework APIs is a good way to customize and fine tune the localizedDescription of an NSError.

As an example, for Foundation error code NSFileWriteOutOfSpaceError, setting the value of this key to "The image library could not be saved." will allow the localizedDescription of the error to come out as "The image library could not be saved. The volume Macintosh HD is out of space." rather than the default (say) “You can't save the file ImgDatabaseV2 because the volume Macintosh HD is out of space."

Upvotes: 3

Related Questions