iosobjective-cnsarraynssortdescriptoralphabetical-sort

Sorting Array Of two different object using NSSortDescriptor


I have an array which have two types of Objects i.e (Object1 , Object2). Object1 has attribute named as "title" and Object2 has attribute named as "name".

Now i want to sort the array alphabetically. So is there any way so that i sort the array containing the objects with different AttributesName using NSSortDescriptor (or any other thing)?


Solution

  • You can use following code to compare your array containing objects of different type and value.

        arraySortedValues = [[arrayValues sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSString *string1 = @"";
            NSString *string2 = @"";
            if ([obj1 isKindOfClass:[Object1 class]]) {
                string1 = [obj1 valueForKey:@"title"];
            }
            if ([obj2 isKindOfClass:[Object1 class]]) {
                string2 = [obj2 valueForKey:@"title"];
            }
            if ([obj1 isKindOfClass:[Object2 class]]) {
                string1 = [obj1 valueForKey:@"name"];
            }
            if ([obj2 isKindOfClass:[Object2 class]]) {
                string2 = [obj2 valueForKey:@"name"];
            }
            return [string1 compare:string2];
        }] mutableCopy];
    

    Hope this helps and let me know.. :)