Sorting and Compare traps in Objective-C

Source: Internet
Author: User
Tags allkeys

Sorting and Compare traps in Objective-C

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


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.