Search code examples
iosobjective-csortingcore-datansset

sorting array using nsset key value


In my project, i am having array of some custom objects.Each object will be in the following format.

 {
enrollementStatus = 0;
enrollementType = 1;
titles =     (
    "0x7b316eb0 <x-coredata://6F003DDD-D6CD-4514-B565-FEF9203F188C/CourseText/p246>"
);}

In this object titles is nsset type.while print this object,It will look like

   ( "<CourseText: 0x7b316f60>
     (entity: CourseText; id: 0x7b316eb0 data: 
    {\n    course = \"0x7aa69870 <x-coredata://6F003DDD-D6CD-4514-B565-FEF9203F188C/Course/p11>\";\n  
  descr = \"(null)\";\n   
     lang = \"en-US\";\n  
      title = CSDFFFFF;\n})"

I want to sort this array based on thistitles(NSSet object) title(alphabetical order).Please give me a suggestion


Solution

  • You can sort the NSSet and create a sorted NSArray using NSSortDescriptor

    NSSortDescriptor *titleSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
    NSArray *sortedObjects = [titles sortedArrayUsingDescriptors:@[titleSortDescriptor]];
    

    Edit 1 Updated answer as per comments :

    As per my understanding your object structure is something like this:

    1. Array of YourCustomObject, where YourCustomObject contains a NSSet called titles.
    2. titles contain an object of class CourseText
    3. CourseText has a property title
    4. You want to Sort Array of YourCustomObject based on the title property of CourseText.

    For this you can use sortedArrayUsingComparator method of NSArray.

    //arrayOfCustomObjects is the array that contains your objects to be sorted
    //Replace YourCustomObject with the actual class of the objects
    NSArray* sortedArray = [arrayOfCustomObjects sortedArrayUsingComparator:^NSComparisonResult(YourCustomObject* obj1, YourCustomObject* obj2) {
    
        NSString* title1 = ((CourseText*)obj1.titles.anyObject).title;
        NSString* title2 = ((CourseText*)obj2.titles.anyObject).title;
    
        return [str1 compare:str2];
    
    }];