Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

objective c - Compare the text of two text fields

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 == passwordConfirmField) {

    //they are equal to each other

} else {

    //they are not equal to each other

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...