简体   繁体   中英

putting two lists of different objects and sort them by date, objective C

List 1 contains a list of object As and list 2 contains a list of object Bs.

Object A contains

date
quantity
message

Object B contains

date
email
first name
last name

Both object As and Bs has a property date in common. Are there anyway to merge them into one list and sorted by date.

You should merge them into one Array (NSArray's arrayByAddingObjectsFromArray:, right?) and then you could use NSArray's sortedArrayUsingComparator:

    NSArray *mergedArray = [array1 arrayByAddingObjectsFromArray:array2];

    NSArray *orderedArray = [mergedArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
        NSDate *date1 = [obj1 date];
        NSDate *date2 = [obj2 date];
        return [date1 compare:date2];
    }];

I haven't tested the code, but it's going to be something like that.

NSArray *listA = [NSArray arrayWithObjects:objA0, objA1, objA2, nil];
NSArray *listB = [NSArray arrayWithObjects:objB0, objB1, objB2, nil];

NSMutableArray *allObjects = [NSMutableArray arrayWithArray:listA];
[allObjects addObjectsFromArray:listB];

[allObjects sortUsingComparator:(NSComparator)^(id obj1, id obj2){
    NSDate *date1 = obj1.date;
    NSDate *date2 = obj2.date;
    return [date1 compare:date2]; }];

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