Sorting Array Of two different object using NSSortDescriptor

727 views Asked by At

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)?

3

There are 3 answers

1
Tejvansh On BEST ANSWER

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.. :)

0
Nandha K On

Sample sorting with custom class attributes

// Sample class 
@interface Class1 : NSObject

@property(nonatomic) NSString *titleStr;

@end  

@interface Class2 : NSObject

@property(nonatomic) NSString *nameStr;

@end  

// Implementation Class

// 1 ======  Pass unsorted array ======

   NSArray sortedArray = [self getSortedArray:objArray];

// 2 Add below methods to your viewcontroller


//Sorting methods
- (NSArray *)getSortedArray:(NSMutableArray *)passedArray {

    NSArray *sortedArray = [passedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

      return [[self getValue:obj1] compare:[self getValue:obj2]];

   }];

   return sortedArray;
}

- (NSString *)getValue:(id)obj {

   NSString *returnStr = @"";

   if ([obj isKindOfClass:[Class1 class]]) {
       returnStr = [obj valueForKey:@"titleStr"];
   }

   if ([obj isKindOfClass:[Class2 class]]) {
       returnStr = [obj valueForKey:@"nameStr"];
   }

   return returnStr;
 }
0
Pradumna Patil On

Try this

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
NSArray *sortedArray = [detailsArray sortArrayUsingDescriptors:@[sortDescriptor]];

Check this link

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html#//apple_ref/doc/uid/20001845-BAJEAIEE