Traps for compare methods in the NSString class of iOS

Source: Internet
Author: User


typedef ns_enum (Nsinteger, nscomparisonresult) {nsorderedascending = -1l, Nsorderedsame, nsordereddescending};

Where Nsorderedsame indicates that the two strings of the comparison are exactly the same, and that in this enumeration, it has a value of 0.

String comparisons are common in programs, such as:

    if ([str1 compare:@ "some text"] = = Nsorderedsame) {        //do something    }    else {        //do something else    }

However, if str1 in the above is nil, the return is nil for any message sent by nil, according to the OBJECTIVE-C message invocation rule (method call). In this case, the runtime will not have a null pointer illegal access in the same way as C/s + +, forcing the program to terminate. That is, under Objective-c, even if str1 is nil, it does not cause the program to crash, but will continue to run.

Then when str1 is empty, the return of the [str1 compare:@ "some text"] message will be nil. Nil represents an empty Objective-c object, which actually represents a null pointer, and it represents a value of 0, equal to the value of Nsorderedsame. So, back to the first if statement, if STR1 is nil, then the value of the entire statement is true. This can cause very serious problems to the program, small logic errors, UI display errors, etc., large can cause data leakage and so on ... So, once this happens, it's still very serious.

I personally suggest that the above code should at least be written as:

    if (Str1!=nil && [str1 compare:@ "some text"] = = Nsorderedsame) {}else{}

Traps for compare methods in the NSString class of iOS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.