iosobjective-csortingnsmutablearraynssortdescriptor

How to sort nsmutablearray with two key values


My NSMutableArray Values as follows

I want to sort this array alphabetically using "category_name" and total_assets > 0.00

Suggest me some sorting code

{
    CID = 1;
    "category_name" = Art;
    "rbg_color" = "1,187,212";
    "total_assets" = "12500.00";
},
{
    CID = 2;
    "category_name" = Automobile;
    "rbg_color" = "244,66,54";
    "total_assets" = "102600.00";
},
{
    CID = 3;
    "category_name" = Banks;
    "rbg_color" = "1,149,135";
    "total_assets" = "0.00";
},
{
    CID = 4;
    "category_name" = Cash;
    "rbg_color" = "75,175,79";
    "total_assets" = "25000.00";
},
{
    CID = 5;
    "category_name" = Clothing;
    "rbg_color" = "103,57,182";
    "total_assets" = "0.00";
},
{
    CID = 7;
    "category_name" = Electronics;
    "rbg_color" = "32,149,242";
    "total_assets" = "0.00";
},

{
    CID = 10;
    "category_name" = Watches;
    "rbg_color" = "139,194,74";
    "total_assets" = "0.00";
},
{
    CID = 11;
    "category_name" = Wine;
    "rbg_color" = "62,80,180";
    "total_assets" = "30500.00";
}

Solution

  • your friends are NSPredicat and NSSortDescriptor you can find Apple documentation for the both in the links provided , an easy way to do that is the following :

    -(void)sortMeyhod
    {
        NSSortDescriptor *sortDescriptor;
       //here you initialize the descriptor with key category_name , and it is case insensitive i.e capital or small
       sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"category_name"
                                               ascending:YES
                                               selector:@selector(caseInsensitiveCompare:)];
       //create your descriptors array .
       sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
       //sort your array . 
       yourArray  = [yourArray sortedArrayUsingDescriptors:sortDescriptors];
        //filter your array with a predicate . 
       NSPredicate * predicate = [NSPredicate predicateWithFormat:@"%K > 0.00" , @"total_assets"] ;
       yourArray =[yourArray filteredArrayUsingPredicate:predicate] ; 
    }
    

    i did not fully test the code but theoretically it should work , and also please refer to the documentation .