106

I have an NSTextField and I need to get the field's value into a variable. What's the appropriate method?

jscs
  • 63,694
  • 13
  • 151
  • 195
anakin
  • 1,189
  • 2
  • 7
  • 8

4 Answers4

117

For an NSString you would use:

NSString *myString = [theTextField stringValue];

For an int you would use:

int myInt = [theTextField intValue];

There are many other methods for getting the value from a control. Have a look at the NSControl reference for more info, under the "Getting and Setting the Control’s Value" section.

Here's a list:

  • doubleValue
  • floatValue
  • intValue
  • integerValue
  • objectValue
  • stringValue
  • attributedStringValue
jscs
  • 63,694
  • 13
  • 151
  • 195
toholio
  • 2,888
  • 2
  • 22
  • 21
7

Swift 3.x Version:

myField.stringValue
Stanley
  • 1,981
  • 3
  • 14
  • 18
3

[myField stringValue]

NSTextField inherits from NSControl, and NSControl defines the stringValue/setStringvalue: methods.

jscs
  • 63,694
  • 13
  • 151
  • 195
Ecton
  • 10,702
  • 2
  • 35
  • 44
0

Also:

Say you have an object (MyObject) that wants to be be notified when someone types into a NSTextField. In the .h file, MyObject should declare it conforms to NSTextFieldDelegate, as in...

@interface MyObject : NSObject <NSTextFieldDelegate>

Then you set MyObject as the delegate of the NSTextField

[myTextField setDelegate:myObject]

Now, you can find out when something happens in the textfield by implementing methods in MyObject like:

-(void)controlTextDidEndEditing:(NSNotification *)aNotification;
-(void)controlTextDidChange:(NSNotification *)aNotification;
-(void)controlTextDidBeginEditing:(NSNotification *)aNotification;
Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
The Cappy
  • 623
  • 4
  • 8