Sort NSMutableArray with strings that contain numbers?

后端 未结 4 1560
北恋
北恋 2021-01-06 02:01

I have a NSMutableArray and it has the users high scores saved into it. I want to arrange the items numerically (the numbers are stored in NSStrings.)
Example:
4,2,7,8

4条回答
  •  无人及你
    2021-01-06 02:13

    If the array is of nsdictionaries conaining numeric value for key number

    isKeyAscending = isKeyAscending ? NO : YES;
    
    [yourArray sortUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    
        NSString *str1 = [obj1 objectForKey:@"number"];
        NSString *str2 = [obj2 objectForKey:@"number"];
    
        if(isKeyAscending) { //ascending order
            return [str1 compare:str2 options:(NSNumericSearch)];
        } else { //descending order
            return [str2 compare:str1 options:(NSNumericSearch)];
        }
    }];
    
    //yourArray is now sorted
    

提交回复
热议问题