遍历数组并存储结果

iterate through array and store results

我有一个名为 thoughtArray 的数组,它是一个名为 ThoughtObject 的自定义对象的数组。 ThoughtObject 有一个名为 'createdDate' 的 属性,它包含一个 NSDate,即对象的创建日期。

我需要过滤该数组并找到与当前日期匹配的所有对象,然后将它们附加到另一个数组。

到目前为止所有的尝试都没有成功。这是我在下面尝试过的。

for createdToday in thoughtArray {
        if (createdToday.createdDate?.isEqualToDate(NSDate()) != nil) {
            createdTodayArray.append(createdToday)

        }
    }

问题是即使将 createdToday 属性 设置为几天前的对象也会添加到数组中。

不胜感激。

一个NSDate对象代表一个特定的时刻。因此,数组中的日期不太可能正好代表现在。

有几种方法可以确定日期是否为今天。你可以把日期变成NSDateComponents然后比较年月日。

有两个问题。首先,"optional chaining"

createdToday.createdDate?.isEqualToDate(NSDate()

returns nil与否,取决于是否createdToday.createdDatenil 还是不是。那不是你想要的。

其次,正如@thelaws 在他的回答中所述,isEqualToDate() returns 只有 yes 如果两个日期代表完全相同的时刻。 NSCalendar 有一个

func compareDate(date1: NSDate, toDate date2: NSDate, toUnitGranularity unit: NSCalendarUnit) -> NSComparisonResult

方法(自 iOS 8 起可用)可在此处使用:

let cal = NSCalendar.currentCalendar()
let now = NSDate()
for createdToday in thoughtArray {
    if let createdAt = createdToday.createdDate {
        // compare with "day granularity":
        if cal.compareDate(createdAt, toDate: now, toUnitGranularity: .CalendarUnitDay) == .OrderedSame {
              createdTodayArray.append(createdToday)
        }
    }
}

使用Martin提到的compareDate函数和Array的过滤函数:

var thoughtArray = [ThoughtObject]()
var cal = NSCalendar.currentCalendar()
var createdToday = thoughtArray.filter {
    if let createdDate = [=10=].createdDate {
        return cal.compareDate(NSDate(), toDate: createdDate, toUnitGranularity: .CalendarUnitDay) == .OrderedSame
    }
    else {
        return false;
    }
}