How do I get the text from UITextField into an NSString?

49,228

Solution 1

Get the text inside the text field using the text property

NSString *name = yourNameField.text;

Solution 2

Use the text property of UITextField:

NSString *userName = yourNameField.text;

Solution 3

How about:

userName = [NSString stringWithFormat:@"%@", yournamefield.text];

Solution 4

Two ways. It is a property and any property value can be accessed like this -

  • yournamefield.text
  • [yournamefield text]
Share:
49,228
Andrew
Author by

Andrew

Updated on March 11, 2020

Comments

  • Andrew
    Andrew about 4 years

    I've tried various methods, which all give me warnings. Such as userName = [NSString stringWithFormat:@"%@", [yournamefield stringValue]]; which just gives me a warning of

    'UITextField' may not respond to '-stringValue'

    How do i do this?

  • PeyloW
    PeyloW over 13 years
    Why use stringWithFormat: if the string the only content of the format string?
  • PeyloW
    PeyloW over 13 years
    No! Do not use the accessor method for something that is explicitly defined as a property in the public header.
  • badgerr
    badgerr over 13 years
    No reason - it was a quick change from his original post :).
  • Admin
    Admin over 13 years
    @PeyloW Can I quickly ask why this is not to be done? Isn't that what a property s doing, generating accessors? Won't the runtime convert the dot syntax to the accessor syntax?
  • PeyloW
    PeyloW over 13 years
    @MattM: Yes it is what the implementation is doing, but you should only think of that as an implementation detail and a side effect of backwards compatibility to Objective-C 1.0. Properties are intended for state, and methods are for behavior. Accessing a property as a method compiles, but your code clearly tells that you misunderstand the APIs intention.
  • Admin
    Admin over 13 years
    I'm afraid I don't agree with you here. Apple's own docs say that the dot syntax is syntactic sugar provided as an alternative to square bracket notation. Admittedly it does have the advantage of the compiler signalling an error when it detects an attempt to write to a read-only declared property, whereas square brackets at best generate an undeclared method warning. However, it certainly does not imply a misunderstanding of the APIs intention.
  • Tricertops
    Tricertops almost 11 years
    @PeyloW Please, look at NSDateComponents and tell me if has state or behavior. Your argument is wrong. Property is term not strictly related to @property syntax. Even in Objective-C 1.0 you used properties, but you had to to write accessors yourself. Dot syntax is just easier way to invoke methods without arguments, but should not be abused for clearly behavioral methods. But this is just styling issue and it works exactly the same. It's not implementation detail. --- Ah, again an old question, that appeared on SO main page :(