简体   繁体   中英

Sorting an NSArray by object type

I have an NSArray that populates a UITableView. One of the fields is an NSString. There is another method that gets called in the cellForRowAtIndexPath: method that changes the color of the NSString based on what the NSString is (it basically determines what values the NSString holds, and sets the color for the label). I'm trying to determine how I can sort by the color in this case since another method determines the color, and even then, the color is just a #define value.

I was thinking of creating an array, where each member would have the color (which is an int value of 0, 1, 2). From there, I could try to sort on these numbers, so all the 0s would be first, then the 1s, then the 2s, or something like that.

However, I do not know how to keep track of everything. Since the array I created only lines up with the original array, if I sort based on this array, how do I get the actual Marker objects to change? I'm not sure if this is the best way, and if it is, how would I keep track of all the sorting. Thanks.

Use the below code as reference to sort your array by color number

 - (NSComparisonResult)compare:(MyClass *) otherObject {
        return [self.colorNum compare:otherObject.colorNum ];
    }

    NSArray *sortedArray;
    mySortedArray = [myUnsortedArray sortedArrayUsingSelector:@selector(compare:)];

Check the below SO post.

How to sort an NSMutableArray of objects by a member of its class, that is an int or float

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