Mac Developer Library

Developer

Foundation Framework Reference NSFormatter Class Reference

Options
Deployment Target:

On This Page
Language:

NSFormatter

NSFormatter is an abstract class that declares an interface for objects that create, interpret, and validate the textual representation of cell contents. The Foundation framework provides two concrete subclasses of NSFormatter to generate these objects: NSNumberFormatter and NSDateFormatter. More...

Conforms To


Import Statement


import Foundation @import Foundation;

Availability


Available in OS X v10.0 and later.
  • The default implementation of this method raises an exception.

    Declaration

    Swift

    func stringForObjectValue(_ anObject: AnyObject) -> String?

    Objective-C

    - (NSString *)stringForObjectValue:(id)anObject

    Parameters

    anObject

    The object for which a textual representation is returned.

    Return Value

    An NSString object that textually represents object for display. Returns nil if object is not of the correct class.

    Discussion

    When implementing a subclass, return the NSString object that textually represents the cell’s object for display and—if editingStringForObjectValue: is unimplemented—for editing. First test the passed-in object to see if it’s of the correct class. If it isn’t, return nil; but if it is of the right class, return a properly formatted and, if necessary, localized string. (See the specification of the NSString class for formatting and localizing details.)

    The following implementation (which is paired with the getObjectValue:forString:errorDescription: example above) prefixes a two-digit float representation with a dollar sign:

    • - (NSString *)stringForObjectValue:(id)anObject {
    • if (![anObject isKindOfClass:[NSNumber class]]) {
    • return nil;
    • }
    • return [NSString stringWithFormat:@"$%.2f", [anObject floatValue]];
    • }

    Import Statement

    import Foundation

    Availability

    Available in OS X v10.0 and later.

  • The default implementation returns nil to indicate that the formatter object does not provide an attributed string.

    Declaration

    Swift

    func attributedStringForObjectValue(_ anObject: AnyObject, withDefaultAttributes attributes: [NSObject : AnyObject]?) -> NSAttributedString?

    Objective-C

    - (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultAttributes:(NSDictionary *)attributes

    Parameters

    anObject

    The object for which a textual representation is returned.

    attributes

    The default attributes to use for the returned attributed string.

    Return Value

    An attributed string that represents anObject.

    Discussion

    When implementing a subclass, return an NSAttributedString object if the string for display should have some attributes. For instance, you might want negative values in a financial application to appear in red text. Invoke your implementation of stringForObjectValue: to get the non-attributed string, then create an NSAttributedString object with it (see initWithString:). Use the attributes default dictionary to reset the attributes of the string when a change in value warrants it (for example, a negative value becomes positive) For information on creating attributed strings, see Attributed String Programming Guide.

    Import Statement

    import Foundation

    Availability

    Available in OS X v10.0 and later.

  • The default implementation of this method invokes stringForObjectValue:.

    Declaration

    Swift

    func editingStringForObjectValue(_ anObject: AnyObject) -> String

    Objective-C

    - (NSString *)editingStringForObjectValue:(id)anObject

    Parameters

    anObject

    The object for which to return an editing string.

    Return Value

    An NSString object that is used for editing the textual representation of anObject.

    Discussion

    When implementing a subclass, override this method only when the string that users see and the string that they edit are different. In your implementation, return an NSString object that is used for editing, following the logic recommended for implementing stringForObjectValue:. As an example, you would implement this method if you want the dollar signs in displayed strings removed for editing.

    Import Statement

    import Foundation

    Availability

    Available in OS X v10.0 and later.

  • The default implementation of this method raises an exception.

    Declaration

    Swift

    func getObjectValue(_ anObject: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool

    Objective-C

    - (BOOL)getObjectValue:(out id *)anObject forString:(NSString *)string errorDescription:(out NSString **)error

    Parameters

    anObject

    If conversion is successful, upon return contains the object created from string.

    string

    The string to parse.

    error

    If non-nil, if there is a error during the conversion, upon return contains an NSString object that describes the problem.

    Return Value

    YEStrue if the conversion from string to cell content object was successful, otherwise NOfalse.

    Discussion

    When implementing a subclass, return by reference the object anObject after creating it from string. Return YEStrue if the conversion is successful. If you return NOfalse, also return by indirection (in error) a localized user-presentable NSString object that explains the reason why the conversion failed; the delegate (if any) of the NSControl object managing the cell can then respond to the failure in control:didFailToFormatString:errorDescription:. However, if error is nil, the sender is not interested in the error description, and you should not attempt to assign one.

    The following example (which is paired with the example given in stringForObjectValue:) converts a string representation of a dollar amount that includes the dollar sign; it uses an NSScanner instance to convert this amount to a float after stripping out the initial dollar sign.

    • - (BOOL)getObjectValue:(id *)obj forString:(NSString *)string errorDescription:(NSString **)error {
    • float floatResult;
    • NSScanner *scanner;
    • BOOL returnValue = NO;
    • scanner = [NSScanner scannerWithString: string];
    • [scanner scanString: @"$" intoString: NULL]; //ignore return value
    • if ([scanner scanFloat:&floatResult] && ([scanner isAtEnd])) {
    • returnValue = YES;
    • if (obj)
    • *obj = [NSNumber numberWithFloat:floatResult];
    • } else {
    • if (error)
    • *error = NSLocalizedString(@"Couldn’t convert to float", @"Error converting");
    • }
    • return returnValue;
    • }

    Special Considerations

    Prior to OS X v10.6, the implementation of this method in both NSNumberFormatter and NSDateFormatter would return YEStrue and an object value even if only part of the string could be parsed. This is problematic because you cannot be sure what portion of the string was parsed. For applications linked on or after OS X v10.6, this method instead returns an error if part of the string cannot be parsed. You can use getObjectValue:forString:range:error: to get the old behavior—it returns the range of the substring that was successfully parsed.

    Import Statement

    import Foundation

    Availability

    Available in OS X v10.0 and later.

  • Returns a Boolean value that indicates whether a partial string is valid.

    Declaration

    Swift

    func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool

    Objective-C

    - (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error

    Parameters

    partialString

    The text currently in a cell.

    newString

    If partialString needs to be modified, upon return contains the replacement string.

    error

    If non-nil, if validation fails contains an NSString object that describes the problem.

    Return Value

    YEStrue if partialString is an acceptable value, otherwise NOfalse.

    Discussion

    This method is invoked each time the user presses a key while the cell has the keyboard focus—it lets you verify and edit the cell text as the user types it.

    In a subclass implementation, evaluate partialString according to the context, edit the text if necessary, and return by reference any edited string in newString. Return YEStrue if partialString is acceptable and NOfalse if partialString is unacceptable. If you return NOfalse and newString is nil, the cell displays partialString minus the last character typed. If you return NOfalse, you can also return by indirection an NSString object (in error) that explains the reason why the validation failed; the delegate (if any) of the NSControl object managing the cell can then respond to the failure in control:didFailToValidatePartialString:errorDescription:. The selection range will always be set to the end of the text if replacement occurs.

    This method is a compatibility method. If a subclass overrides this method and does not override isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange:errorDescription:, this method will be called as before (isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange:errorDescription: just calls this one by default).

    Import Statement

    import Foundation

    Availability

    Available in OS X v10.0 and later.

  • This method should be implemented in subclasses that want to validate user changes to a string in a field, where the user changes are not necessarily at the end of the string, and preserve the selection (or set a different one, such as selecting the erroneous part of the string the user has typed).

    Declaration

    Swift

    func isPartialStringValid(_ partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString?>, proposedSelectedRange proposedSelRangePtr: NSRangePointer, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool

    Objective-C

    - (BOOL)isPartialStringValid:(NSString **)partialStringPtr proposedSelectedRange:(NSRangePointer)proposedSelRangePtr originalString:(NSString *)origString originalSelectedRange:(NSRange)origSelRange errorDescription:(NSString **)error

    Parameters

    partialStringPtr

    The new string to validate.

    proposedSelRangePtr

    The selection range that will be used if the string is accepted or replaced.

    origString

    The original string, before the proposed change.

    origSelRange

    The selection range over which the change is to take place.

    error

    If non-nil, if validation fails contains an NSString object that describes the problem.

    Return Value

    YEStrue if partialStringPtr is acceptable, otherwise NOfalse.

    Discussion

    In a subclass implementation, evaluate partialString according to the context. Return YEStrue if partialStringPtr is acceptable and NOfalse if partialStringPtr is unacceptable. Assign a new string to partialStringPtr and a new range to proposedSelRangePtr and return NOfalse if you want to replace the string and change the selection range. If you return NOfalse, you can also return by indirection an NSString object (in error) that explains the reason why the validation failed; the delegate (if any) of the NSControl object managing the cell can then respond to the failure in control:didFailToValidatePartialString:errorDescription:.

    Import Statement

    import Foundation

    Availability

    Available in OS X v10.0 and later.

  • Specifies the width of the unit, determining the textual representation.

    Declaration

    Swift

    enum NSFormattingUnitStyle : Int { case Short case Medium case Long }

    Objective-C

    enum { NSFormattingUnitStyleShort = 1, NSFormattingUnitStyleMedium, NSFormattingUnitStyleLong, }; typedef NSUInteger NSFormattingUnitStyle;

    Constants

    • Short

      NSFormattingUnitStyleShort

      Specifies a short width.

      The corresponding value is an NSInteger, equal to 1.

      Available in OS X v10.10 and later.

    • Medium

      NSFormattingUnitStyleMedium

      Specifies a medium width.

      The corresponding value is an NSInteger, equal to 2.

      Available in OS X v10.10 and later.

    • Long

      NSFormattingUnitStyleLong

      Specifies a long width.

      The corresponding value is an NSInteger, equal to 3.

      Available in OS X v10.10 and later.

    Discussion

    The unit is represented in the shortest notation available. For example, for English, when formatting "3 pounds": NSFormattingUnitStyleLong is "3 pounds"; NSFormattingUnitStyleMedium is "3 lb"; NSFormattingUnitStyleShort is "3#".

    Import Statement

    import Foundation

    Availability

    Available in OS X v10.10 and later.

  • Specifies the capitalization context.

    Declaration

    Swift

    enum NSFormattingContext : Int { case Unknown case Dynamic case Standalone case ListItem case BeginningOfSentence case MiddleOfSentence }

    Objective-C

    enum { NSFormattingContextUnknown = 0, NSFormattingContextDynamic = 1, NSFormattingContextStandalone = 2, NSFormattingContextListItem = 3, NSFormattingContextBeginningOfSentence = 4, NSFormattingContextMiddleOfSentence = 5, }; typedef NSUInteger NSFormattingContext;

    Constants

    • Unknown

      NSFormattingContextUnknown

      Specifies the capitalization context to be used is unknown.

      This is the default value. The corresponding value is an NSInteger, equal to 0.

      Available in OS X v10.10 and later.

    • Dynamic

      NSFormattingContextDynamic

      Specifies an undetermined format.

      The capitalization context is determined dynamically from the set {NSFormattingContextStandalone, NSFormattingContextBeginningOfSentence, NSFormattingContextMiddleOfSentence}.

      When the string proxy is used in stringWithFormat:, the formatter returns a string proxy for a generic string and then formats the string using NSFormattingContextUnknown. The formatter derives the context from the generic string’s location and then formats the string appropriately.

      The corresponding value is an NSInteger, equal to 1.

      Available in OS X v10.10 and later.

    • Standalone

      NSFormattingContextStandalone

      Specifies formatting for the beginning of a sentences.

      The capitalization context if a date or date symbol is to be formatted with capitalization appropriate for stand-alone usage such as an isolated name on a calendar page.

      The corresponding value is an NSInteger, equal to 2.

      Available in OS X v10.10 and later.

    • ListItem

      NSFormattingContextListItem

      Specifies formatting for a list or menu.

      The capitalization context if a date or date symbol is to be formatted with capitalization appropriate for a list or menu item.

      The corresponding value is an NSInteger, equal to 3.

      Available in OS X v10.10 and later.

    • BeginningOfSentence

      NSFormattingContextBeginningOfSentence

      Specifies formatting for the beginning of a sentence.

      The capitalization context if a date or date symbol is to be formatted with capitalization appropriate for the beginning of a sentence.

      The corresponding value is an NSInteger, equal to 4.

      Available in OS X v10.10 and later.

    • MiddleOfSentence

      NSFormattingContextMiddleOfSentence

      Specifies formatting for the middle of a sentence.

      The capitalization context if a date or date symbol is to be formatted with capitalization appropriate for the middle of a sentence.

      The corresponding value is an NSInteger, equal to 5.

      Available in OS X v10.10 and later.

    Import Statement

    import Foundation

    Availability

    Available in OS X v10.10 and later.