简体   繁体   中英

can I sort NSMutable array of NSStrings by their substrings using the selector (in place)?

I have a NSMutableArray consisting out of NSString s. When I need to sort it, I use [array sortUsingSelector:@selector(caseInsensitiveCompare:)] which works perfect.

But sometimes I need to sort the array by substrings of NSString s. The substring is defined in this case as part of NSString following some marker. The thing is complicated further by the fact that marker can be positioned differently in every string.

Obviously I can break NSString into 2 objects and do sorting on them but it will require significant changes.

Is there a way to do the sorting using selector similar to what I have described above?

I think if not, then I might sort by creating a sorted copy of an array (instead of using selector to do it in place), then releasing the original.

You can perform any arbitrarily complex sorting inline with NSMutableArray's sortWithOptions:usingComparator :

[myMutableArray sortWithOptions:NSSortStable usingComparator:^NSComparisonResult(NSString* str1, NSString* str2) {

    // Scan for your marker in both strings and split on it...
    // Say you store the results in substr1 and substr2...
    return [substr1 caseInsensitiveCompare:substr2];
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM