简体   繁体   中英

Sorting Array Of two different object using NSSortDescriptor

I have an array which have two types of Objects ie (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)?

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

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

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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM