Sorting and compare traps in objective-C

Source: Internet
Author: User
Tags allkeys

Campare trap

Nsstring has multiple compare related methods:
-(Nscomparisonresult) Compare :( nsstring *) string;
-(Nscomparisonresult) Compare :( nsstring *) string options :( nsstringcompareoptions) mask;
-(Nscomparisonresult) Compare :( nsstring *) string options :( nsstringcompareoptions) mask range :( nsange) comparerange;
-(Nscomparisonresult) Compare :( nsstring *) string options :( nsstringcompareoptions) mask range :( nsange) comparerange locale :( ID) locale;

Nscomparisonresult is an enumeration defined as follows:
Typedef ns_enum (nsinteger, nscomparisonresult) {nsorderedascending =-1l, nsorderedsame, nsordereddescending };
Here, nsorderedsame indicates that the two strings to be compared are exactly the same. Meanwhile, in this enumeration, its value is 0.
Strings are quite common in programs, such:
If ([str1 compare: @ "some text"] = nsorderedsame ){
// Todo
}
Else {
// Todo
}
However, if str1 in the preceding example is nil, according to the message calling rule (method call) of objective-C, any message sent to nil will return nil. In this case, the program will not be forcibly terminated due to illegal access to null pointers like C/C ++. That is to say, under Objective-C, even if str1 is nil, it will not cause program crash, but will continue to run.
If str1 is null, the return value of the [str1 compare: @ "some text"] Message is nil. Nil indicates an empty objective-C object, which actually represents a null pointer, and its value is 0, which is equal to the value of nsorderedsame. in this case, return to the first if statement. If str1 is nil, the value of the entire statement is true. This will cause very serious problems to the program, such as logical errors, UI display errors, and data leakage... Therefore, once this happens, it is still very serious.
I personally suggest that the above Code should at least be written:
If (str1! = Nil & [str1 compare: @ "some text"] = nsorderedsame ){
// Todo

}

Else {
// Todo
}


OC sorting code, directly on the code

// Sort numbers

-(Void) sortnumber {

Nsarray * originalarray = @ [@ "8", @ "41", @ "32", @ "11", @ "-1"];

// Block comparison method, which can be nsinteger or cgfloat in the array (need to be converted)

Nscomparator findersort = ^ (ID string1, Id string2 ){

If ([string1 integervalue]> [string2integervalue]) {

Return (nscomparisonresult) nsordereddescending;

} Else if ([string1integervalue] <[string2integervalue]) {

Return (nscomparisonresult) nsorderedascending;

}

Else

Return (nscomparisonresult) nsorderedsame;

};

Nsarray * resultarray = [originalarray sortedarrayusingcomparator: findersort];

Nslog (@ "sorting result: % @", resultarray );

}


// Sort strings

-(Void) sortstring {

// 2. Non-numeric string (note that empty data (NiL) should be excluded for comparison with compare ))

Nsarray * chararray = @ [@ "string 1", @ "string 21", @ "string 12", @ "string 11", @ "string 02"];

Nsstringcompareoptions comparisonoptions = nscaseinsensitivesearch | nsnumericsearch |

Nswidthinsensitivesearch | nsforcedorderingsearch;

Nscomparator sort = ^ (nsstring * obj1, nsstring * obj2 ){

Nsange range = nsmakerange (0, obj1.length );

Return [obj1 compare: obj2options: comparisonoptionsrange: range];

};

Nsarray * resultarray2 = [chararray sortedarrayusingcomparator: Sort];

Nslog (@ "string sorting % @", resultarray2 );

}


// Sort the dictionary

-(Void) sortdicrionary {

Nsmutablearray * array = [nsmutablearrayarraywithobjects:

@ {@ "Obj0": @ "0 "},

@ {@ "Obj3": @ "3 "},

@ {@ "Obj1": @ "1 "},

@ {@ "Obj2": @ "2 "},

@ {@ "Obj4": @ "4 "},

Nil];

Nsarray * resultarray = [array sortedarrayusingcomparator: ^ nscomparisonresult (ID obj1, Id obj2 ){

Nsnumber * number1 = [[obj1 allkeys] objectatindex: 0];

Nsnumber * number2 = [[obj2 allkeys] objectatindex: 0];

Nscomparisonresult result = [number1compare: number2];

// Return result = nsorderedascending; // descending order

Return result = nsordereddescending; // ascending

}];

Nslog (@ "ordereddescending: % @", resultarray );

}


// Sort custom objects

-(Void) sortcustomobject {

Slperson * person1 = [[slpersonalloc] init];

[Person1 setname: @ "ABCD"];

[Person1 setage: 24];


Slperson * person2 = [[slpersonalloc] init];

[Person2 setname: @ "acbd"];

[Person2 setage: 22];

Slperson * person3 = [[slpersonalloc] init];

[Person3 setname: @ "ABDC"];

[Person3 setage: 33];

Slperson * person4 = [[slpersonalloc] init];

[Person4 setname: @ "ACDB"];

[Person4 setage: 22];

Nsmutablearray * array = [nsmutablearrayarraywithobjects: person1, person3, person4, person2, nil];

Nssortdescriptor * sortdescriptor1 = [nssortdescriptorsortdescriptorwithkey: @ "Age" ascending: Yes]; // sort by age first,

Nssortdescriptor * sortdescriptor2 = [nssortdescriptorsortdescriptorwithkey: @ "name" ascending: Yes]; // if the age is the same, sort by name, and so on

Nsarray * temparray = [array sortedarrayusingdescriptors: [nsarray arraywithobjects: sortdescriptor1, sortdescriptor2, nil];

For (nsinteger I = 0; I <[temparraycount]; I ++ ){

Nslog (@ "% @ -------- % d \ n", [[temparrayobjectatindex: I] Name], [[temparrayobjectatindex: I] age]);

}

}


Code link: http://download.csdn.net/detail/u011883764/7827311


Sorting and compare traps in objective-C

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.