0

I'm trying to sort the "Transaction" data on the iOS client base on the pushID since it's created base on timestamp:

"Transaction" : {
    "-LENv2bwDAwH43w9XgCx":{
        "amount": 1000,
        timeStamp: 1526699894096 // generated by admin.database.ServerValue.TIMESTAMP
    },
    "-LENxaYGyAqfbUg7enN7":{
        "amount": 1500,
        timeStamp: 7528362568524
    },
    "-LEOVVgvJaiWkMDb__eF":{
        "amount": 2000,
        timeStamp: 8528353417439
    },
}

I've tried to create 2 arrays, one to store the transaction id and one to store the corresponding transaction data dictionary:

    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorJson];

            NSArray *sortedKeys = [[responseDict allKeys] sortedArrayUsingSelector: @selector(compare:)];
            _transactionKeyArray = [sortedKeys mutableCopy];
            _transactionArray = [NSMutableArray array];
            for (NSString *key in _transactionKeyArray){
                [_transactionArray addObject: [responseDict objectForKey: key]];
            };

However, I found out that after sorting it base on the pushID (e.g. -LENv2bwDAwH43w9XgCx), the sequence is incorrect.

Base on this blog post seems like we need to sort it base on the firebase timestamp (https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html)

How should we sort it base on the timestamp? I need the transaction ID to be sorted as well.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user1872384
  • 6,886
  • 11
  • 61
  • 103

1 Answers1

0

First of all, the dictionaries are not ordered in Objective-C, so to sort it you first need to convert your dictionary to an array. Possibly an array of dictionaries where each element is a dictionary with keys: "amount", "timeStamp" and "pushID":

NSMutableArray *transactionItems = [NSMutableArray new];
for (NSString *pushID in responseDict[@"Transaction"]) {
    // copy amount and timeStamp
    NSMutableDictionary *transactionItem = [responseDict[pushID] mutableCopy];
    transactionItem["pushID"] = pushID;
    [transactionItems addObject:transactionItem];
}

Then you can sort this array using NSSortDescriptor with "timeStamp" as its key. See Sort NSArray of NSDictionary objects using NSSortDescriptor

battlmonstr
  • 5,841
  • 1
  • 23
  • 33