Last active
August 29, 2015 14:14
-
-
Save roothybrid7/faf559f29a70049493f2 to your computer and use it in GitHub Desktop.
ソート済みのNSArrayに、順番を保ちつつ新しいデータを追加する ref: http://qiita.com/roothybrid7/items/15fd39af876a9b7caa90
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSArray *sourceData = @[ | |
@{@"id": @"A", @"createdAt": @1234533333}, | |
@{@"id": @"B", @"createdAt": @1234599999}, | |
@{@"id": @"C", @"createdAt": @1234511111}, | |
@{@"id": @"D", @"createdAt": @1234522222}, | |
@{@"id": @"E", @"createdAt": @1234599999}, | |
]; | |
// Sort descritors | |
NSSortDescriptor *createdAtSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO]; | |
NSSortDescriptor *idSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]; | |
// 並び替え(作成日降順、ID昇順) | |
NSMutableArray *objects = [sourceData sortedArrayUsingDescriptors:@[createdAtSortDescriptor, idSortDescriptor]].mutableCopy; | |
/*! -> | |
@[ | |
@{@"id": @"B", @"createdAt": @1234599999}, | |
@{@"id": @"E", @"createdAt": @1234599999}, | |
@{@"id": @"A", @"createdAt": @1234533333}, | |
@{@"id": @"D", @"createdAt": @1234522222}, | |
@{@"id": @"C", @"createdAt": @1234511111}, | |
]; | |
*/ | |
// 新規データ | |
NSDictionary *newObject = @{@"id": @"F", @"createdAt": @1234544444}; | |
// NSBinarySearchingFirstEqualも合わせて指定すると最初にマッチしたIndexを返す | |
NSUInteger searchOptions = NSBinarySearchingInsertionIndex | NSBinarySearchingFirstEqual; | |
// 追加するデータのIndexの取得 | |
NSInteger newIndex = [objects indexOfObject:newObject inSortedRange:NSMakeRange(0, objects.count) options:searchOptions usingComparator:^NSComparisonResult(NSDictionary *d1, NSDictionary *d2) { | |
if (![d1[@"createdAt"] isEqualToNumber:d2[@"createdAt"]]) { | |
return [d2[@"createdAt"] compare:d1[@"createdAt"]]; | |
} | |
return [d1[@"id"] localizedCaseInsensitiveCompare:d2[@"id"]]; | |
}]; | |
// -> 2 | |
[objects insertObject:newObject atIndex:newIndex]; | |
/*! -> | |
@[ | |
@{@"id": @"B", @"createdAt": @1234599999}, | |
@{@"id": @"E", @"createdAt": @1234599999}, | |
@{@"id": @"F", @"createdAt": @1234544444}, | |
@{@"id": @"A", @"createdAt": @1234533333}, | |
@{@"id": @"D", @"createdAt": @1234522222}, | |
@{@"id": @"C", @"createdAt": @1234511111}, | |
]; | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment