Swift- 最新通知附加到数组后,所有 UILocalNotification 时间都发生了变化

Swift- All UILocalNotification times changed after latest notification is appended to array

我有一个 NSDates 的数组,我正在迭代它以创建一个 UILocalNotification 的数组,然后我使用 scheduledLocalNotifications.

批量安排它

创建通知时,它具有正确的日期。但是,一旦它被附加到数组中,所有已经存在的通知也会在那个日期出现。

func scheduleMessageNotifications() {
    let randomTimes = getSemiRandomTimes() //This function generates an array of unique NSDates which all occur after "now" 
    let notification = UILocalNotification()
    var notifications = [UILocalNotification]()

    for time in randomTimes {

        let nextTime = time
        notification.alertBody = "notification"
        notification.fireDate = nextTime
        //Here the notification has the correct date from randomTimes

        notifications.append(notification)
        //Here the array of notifications all contain the same date; the on that the last notification just had
    }
    UIApplication.sharedApplication().scheduledLocalNotifications = notifications
}

我已尝试清理构建文件夹、删除派生数据并重新启动计算机。我还尝试使循环尽可能简单,同时仍保持其功能。我正在函数内部创建通知数组,而不是调用它或将其发送到其他地方。

有人建议我的 time 可能是参考,因此会影响其余对象。但是在阅读了一些 Apple 文档 (Iterating Over an Array and For-In Loops) 之后,我无法验证这是否属实。 (或者该怎么办。)我确实尝试过

let nextTime = time

但这似乎并没有什么不同。哦,我知道我不会发出超过 64 条通知。 (无法想象为什么会有不同,但我认为它可能会出现。)

任何帮助或想法将不胜感激。

您不是在创建多个通知,而是在创建一个通知并将其一次又一次地附加到数组中。

您生成的数组包含对同一对象的多个引用。如果您随后更改该对象的 date,所有通知将具有相同的 date,因为它们是同一个对象。

var notifications = [UILocalNotification]()

for time in randomTimes {
    // move notification creation inside the loop
    let notification = UILocalNotification()

    let nextTime = time
    notification.alertBody = "notification"
    notification.fireDate = nextTime
    //Here the notification has the correct date from randomTimes

    notifications.append(notification)
    //Here the array of notifications all contain the same date; the on that the last notification just had
}

您也可以使用 map 调用:

let notifications: [UILocalNotification] = randomTimes.map { time in
    let notification = UILocalNotification()

    let nextTime = time
    notification.alertBody = "notification"
    notification.fireDate = nextTime

    return notification
}