简体   繁体   中英

Sorting Objects in NSArray

I have an NSArray with 3 objects in it. Each object is made up of 5 values. How can I sort by Date with in the objects?

result: (
    gg,
    "2012-10-28 01:34:00 +0000",
    "Church Bells",
    "pin_red",
    1
)(
    iu,
    "2008-09-22 17:32:00 +0000",
    "Birthday Song",
    "pin_red",
    1
)(
    "my birthday woo hoo",
    "2012-09-04 19:27:00 +0000",
    "Birthday Song",
    "pin_blue",
    1
)

The results I am looking for - Sorted Array should look like this.

(
    iu,
    "2008-09-22 17:32:00 +0000",
    "Birthday Song",
    "pin_red",
    1
)
(
    "my birthday woo hoo",
    "2012-09-04 19:27:00 +0000",
    "Birthday Song",
    "pin_blue",
    1
)
(
    gg,
    "2012-10-28 01:34:00 +0000",
    "Church Bells",
    "pin_red",
    1
)

I am getting this array from my nsdictionary object.

dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:stringsPlistPath];
stringsMutableArray = [[NSMutableArray alloc] initWithObjects:nil];

        for (id key in dictionary) 
        {
            [stringsMutableArray addObject:[dictionary objectForKey:key]];
        }

Try this:

NSArray *sortedArray = [result sortedArrayUsingComparator: ^(id obj1, id obj2) {
    NSArray *arr1 = (NSArray *)obj1;
    NSArray *arr2 = (NSArray *)obj2;
    NSDate *date1 = arr1[1];
    NSDate *date2 = arr2[1];

    return [date1 compare:date2];
}];

This code assumes you actually have an array of arrays and the dates are NSDate objects always at index 1 in the inner arrays. If this sorts in the opposite order you want, swap the two dates for the date comparison.

Here's a similar question that solves your issue: Sort NSArray of date strings or objects

I'll paste the answer from the above link below:

Store the dates as NSDate objects in an NS(Mutable)Array, then use [ -[NSArray sortedArrayUsingSelector: ][1] or [ -[NSMutableArray sortUsingSelector:] ][1] and pass @selector(compare:) as the parameter. The [ -[NSDate compare:] ][2] method will order dates in ascending order for you. This is simpler than creating an NSSortDescriptor, and much simpler than writing your own comparison function. (NSDate objects know how to compare themselves to each other at least as efficiently as we could hope to accomplish with custom code.)

[1]: http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/sortUsingSelector : [2]: http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/compare :

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