通过 NSDate 从 NSDictionary 加载 UITableView 部分?

Load UITableView sections by NSDate from NSDictionary?

我的应用程序中有一个 NSArray of NSDictionaries。在每本字典中,我都有一个名为 "RunDate." 的 NSDate。我现在遇到的问题是我尝试使用的代码效率非常低。基本上我只想要所有词典中每个日期的一个部分。然后在每个部分(按该日期排序),我将加载具有该日期的相应词典。

在下面的代码中,我创建了一个新的 NSArray of NSDictionarys,其中包含日期和该日期的编号(因此我可以知道每个部分中有多少行)。问题是,这段代码看起来和感觉起来都非常低效,我想知道我的代码是否有任何不正确或可以改进的地方。可以有超过 500 个条目,我现在的代码会非常慢。有人对此有什么建议吗?

    runArray = [[NSMutableArray alloc] init];
    runArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"RunArray"] mutableCopy];

    runDictTableArray = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in runArray) {
        NSDictionary *runInfoDict = [[NSMutableDictionary alloc] init];
        NSDate *theDate = [dict objectForKey:@"RunDate"];

        //Check if we already have this date in the saved run array
        BOOL goToNextDict = FALSE;
        for (NSDictionary *savedDict in runDictTableArray) {
            if ([theDate compare:[savedDict objectForKey:@"RunDate"]] == NSOrderedSame) {
                goToNextDict = TRUE;
                break;
            }
        }
        if (goToNextDict)
            continue;
        ////////////////////////////

        //Now we check how many more we have of this date
        int numbOfDate = 1;
        int index = (int)[runArray indexOfObject:dict];
        for (int i = index; i < [runArray count]; i++) {
            NSDictionary *dictInner = [runArray objectAtIndex:i];
            if ([theDate compare:[dictInner objectForKey:@"RunDate"]] == NSOrderedSame) {
                numbOfDate++;
            }
        }
        ////////////////////////////

        [runInfoDict setValue:[NSNumber numberWithInt:numbOfDate] forKey:@"DateAmount"];
        [runInfoDict setValue:theDate forKey:@"Date"];
        [runDictTableArray addObject:runInfoDict];
    } 

一些建议:

  1. 您可能只需要 1 个 NSMutableDictionary,而不是 NSMutableArrayNSDictionary。在遍历 runArray 时,检查您的字典是否有您日期的值(objectForKey returns 一个值)。如果是,则将计数加 1。如果没有,则将该日期作为键添加到字典中,值为 1。这样,您就不必执行内部循环来获取日期出现的次数。我想你也不需要 'go to next dictionary' 逻辑。
  2. runArray = [[NSMutableArray alloc] init]; 并没有真正做任何事情,因为你立即重新分配 runArray.
  3. 考虑使用 NSInteger 而不是常规 intNSInteger 将为您提供适合您的应用 运行 的任何架构的大小。
  4. 您可能会喜欢一些很酷的语法快捷方式。您可以通过简单地编写 [runInfoDict setValue:@(numbOfDate) ... 来避免 [runInfoDict setValue:[NSNumber numberWithInt:numbOfDate]...,这将为您将值放入 NSNumber