Search code examples
objective-csortingnsarray

Extension for category NSMutableArray Objective-C


I am a beginner programmer and I was given the assignment to write an extension to the category NSMutableArray. In googled it, i found very little information and did not understand how to do it. I need to write an extension to Shell sort. I could use NSSortDescriptor, but expansion should be given the sort algorithm, a standard NSSortDescriptor method is not applicable for this. If there is some sort of a normal user Associative References and how to use it, it is really helped. Because, what I found - is not for me.


Solution

  • So here it is...

    NSMutableArray+Sort.h

    #import <Foundation/Foundation.h>
    @interface NSMutableArray (Sort)
    
        -(void)sortArrayUsingShellSort;
    
    @end
    

    NSMutableArray+Sort.m

    #import "NSMutableArray+Sort.h"
    @implementation NSMutableArray (Sort)
    
        -(void)sortArrayUsingShellSort
        {
             // tasks
             // #1. access the unsorted array using self
             // #2. sort the array using your shell sort, no one gonna do that for you, you have to do that yourself. Re-arrange the items or the array.
    
        }
    
    @end
    

    some useful link for shell sort

    1. Tutorials point
    2. interactivepuython
    3. Wikipedia
    4. Toptal

    Into your main.m

    #import <Foundation/Foundation.h> // not necessary actually, as it is already imported into our NSMutableArray+Sort.h
    #import "NSMutableArray+Sort.h"
    
    int main(int argc, char * argv[]) {
    
        NSMutableArray *myArray = [[NSMutableArray alloc] initWithArray:@[
                                                [NSNumber numberWithInt:10],
                                                [NSNumber numberWithInt:3],
                                                [NSNumber numberWithInt:4],
                                                [NSNumber numberWithInt:15]
                                                ]];
    
    
        NSLog(@"array before sorting %@", myArray);
    
        //here goes your sorting category function call
        [myArray sortArrayUsingShellSort];
    
        NSLog(@"array after sorting %@", myArray);
    }