Search code examples
iosobjective-csortingnsarray

NSArray of Objects sorting with Custom Logic


I have NSSArray having Custom Objects, To sort the Custom Object with Custom logic

Custom object having two property:
@property (nonatomic, strong) NSString *objectName;
@property (nonatomic, assign) BOOL isValidName;

if isValidName property is false, Then the custom object should be last sorting order. for the objects isValidName property is true, Then it should be sort with property objectName in ascending.

I can do with for loop by finding objects having property isValidName false then remove the objects from the array and then sort the array after that I can add the objects which are having property isValidName false. I don't want to do that.

I want that something like below option, But it is not working. Please help in regard

[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *sortedTopics = [obj sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
             if (obj1.isValidName) {  
                return NSOrderedAscending;
            }
            return [obj1.objectName compare: obj2.objectName options:NSCaseInsensitiveSearch];
        }];
        obj = sortedTopics;

    }];

Solution

  • I dont really recreated the stuff you did, but i hope this would work for you: arr should be NSMutableArray

    NSSortDescriptor *validSort = [[NSSortDescriptor alloc] initWithKey:@"isValidName" ascending:NO];
    NSSortDescriptor *nameSort = [[NSSortDescriptor alloc] initWithKey:@"objectName" ascending:YES];
    
    [arr sortUsingDescriptors:[NSArray validSort, nameSort, nil]];
    

    So if your object.isValidName = false it will push to after the one have it true and also sort by name