Compare the text of two text fields

后端 未结 2 373
再見小時候
再見小時候 2020-12-11 23:12

How do you compare the text in two text fields to see if they are the same, such as in \"Password\" and \"Confirm Password\" text fields?

if (passwordField =         


        
相关标签:
2条回答
  • 2020-12-11 23:26

    In Objective-C you should use isEqualToString:, like so:

    if ([passwordField.text isEqualToString:passwordConfirmField.text]) {
        //they are equal to each other
    } else {
        //they are *not* equal to each other
    }
    

    NSString is a pointer type. When you use == you are actually comparing two memory addresses, not two values. The text properties of your fields are 2 different objects, with different addresses.
    So == will always1 return false.


    In Swift things are a bit different. The Swift String type conforms to the Equatable protocol. Meaning it provides you with equality by implementing the operator ==. Making the following code safe to use:

    let string1: String = "text"
    let string2: String = "text"
    
    if string1 == string2 {
        print("equal")
    }
    

    And what if string2 was declared as an NSString?

    let string2: NSString = "text"
    

    The use of == remains safe, thanks to some bridging done between String and NSString in Swift.


    1: Funnily, if two NSString object have the same value, the compiler may do some optimization under the hood and re-use the same object. So it is possible that == could return true in some cases. Obviously this not something you want to rely upon.

    0 讨论(0)
  • 2020-12-11 23:34

    You can do this by using the isEqualToString: method of NSString like so:

    NSString *password = passwordField.text;
    NSString *confirmPassword = passwordConfirmField.text;
    
    if([password isEqualToString: confirmPassword]) {
        // password correctly repeated
    } else {
        // nope, passwords don't match
    }
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题