objective-ccocoanstextfieldnsformatter

Accessing `stringValue` of a NSTextField with custom NSFormatter, in `controlTextDidChange` method makes it non-editable.


I have a custom NSFormatter for a textfield as described in here & here. I also have delegate for this textfield, and I am accessing stringValue from delegate method controlTextDidChange:. With this code when I try to edit the textfield it is continuously resetting it's value from the NSFormatter and making it non-editable.

CustomFormatter.m

 @implementation CustomFormatter

- (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;
}

- (NSString *)stringForObjectValue:(id)anObject {

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

@end

MyDelegate.m

@interface MyController () <NSTextFieldDelegate>
@property (weak) IBOutlet NSTextField *text1;    
@end

@implementation MyController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
}

- (void)controlTextDidChange:(NSNotification *)obj {
    NSLog(@"%@",[self.text1 stringValue]);
}
@end

Solution

  • You can get the string from the field editor, a NSTextView. You can get the field editor from the userinfo of the notification.

    controlTextDidChange

    This method is invoked when text in a control such as a text field or form changes. The control posts a textDidChangeNotification notification, and if the control’s delegate implements this method, it is automatically registered to receive the notification. Use the key @"NSFieldEditor" to obtain the field editor from the userInfo dictionary of the notification object.