我试图对"交易进行排序" iOS客户端上的数据基于pushID,因为它基于时间戳创建:
"Transaction" : {
"-LENv2bwDAwH43w9XgCx":{
"amount": 1000,
timeStamp: 1526699894096 // generated by admin.database.ServerValue.TIMESTAMP
},
"-LENxaYGyAqfbUg7enN7":{
"amount": 1500,
timeStamp: 7528362568524
},
"-LEOVVgvJaiWkMDb__eF":{
"amount": 2000,
timeStamp: 8528353417439
},
}
我试图创建2个数组,一个存储事务ID,另一个存储相应的事务数据字典:
[[[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]];
};
但是,我发现在根据pushID对其进行排序后(例如-LENv2bwDAwH43w9XgCx),序列不正确。
基于此博客帖子似乎我们需要根据firebase时间戳(https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html)对其进行排序
我们应该如何根据时间戳对其进行排序?我还需要对交易ID进行排序。
答案 0 :(得分:0)
首先,字典不是在Objective-C中排序的,所以要对它进行排序,首先需要将字典转换为数组。可能是一个字典数组,其中每个元素都是带有键的字典:" amount"," timeStamp"和" 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];
}
然后你可以使用NSSortDescriptor对这个数组进行排序" timeStamp"作为关键。见Sort NSArray of NSDictionary objects using NSSortDescriptor