每个CollectionView Cell的唯一计时器

时间:2017-11-01 16:18:47

标签: ios swift timer uicollectionview

我正在构建聊天应用,并希望在开启开关时为消息添加自动删除功能。到目前为止,我的代码一次只能处理一条消息,但是当您在第一个计时器完成之前发送2条或更多消息时,它们似乎会相互干扰,尽管在每个单元格内声明了Timer对象。

在cellForItem的collectionView里面我设置了单元格,我检查开关是否在

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ChatMessageCell

        if UserDefaults.standard.value(forKey: "autoDeletion") as? Bool ?? false
        {
            cell.addAutoDeletionTimer()
        }

因此,如果我执行了ChatMessageCell类中的addAutoDeletionTimer()函数,它看起来像这样:

var deletionTimer: Timer?
var timeLeft = 0

func addAutoDeletionTimer()
{
    autoDeletionTimerLabel.isHidden = false
    let currentTime = Int(Date().timeIntervalSince1970)
    let deletionTime = message?.autoDeletion?.intValue
    timeLeft = deletionTime! - currentTime
    if timeLeft > 1
    {
        deletionTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(autoDeletionTimer), userInfo: nil, repeats: true)
    }
    else
    {
        self.chatLogController?.removeMessage(message: message!)
    }
}

@objc func autoDeletionTimer()
{
    timeLeft -= 1
    if timeLeft < 1
    {
        deletionTimer?.invalidate()
        self.chatLogController?.removeMessage(message: message!)
    }
    autoDeletionTimerLabel.text = String(timeLeft)
}

基本上,消息对象有一个名为autoDeletion的属性,例如timerIntervalSince1970 + 120。因此,邮件将在发送后2分钟删除。

正如我所说,如果我只发送1条消息,并等待该消息被删除,则此方法有效。我的问题是如何为每个细胞创建一个独特的计时器,它不会相互干扰? 或者有更好的解决方案吗?

我的留言对象:

class Message: NSObject
{
    var fromId: String?
    var text: String?
    var timestamp: NSNumber?
    var autoDeletion: NSNumber?
    var imageUrl: String?
    var videoUrl: String?
    var imageWidth: NSNumber?
    var imageHeight: NSNumber?
    var messageId: String?

    init(dictionary: [String: Any])
    {
        self.fromId = dictionary["fromId"] as? String
        self.text = dictionary["text"] as? String
        self.timestamp = dictionary["timestamp"] as? NSNumber
        self.imageUrl = dictionary["imageUrl"] as? String
        self.videoUrl = dictionary["videoUrl"] as? String
        self.imageWidth = dictionary["imageWidth"] as? NSNumber
        self.imageHeight = dictionary["imageHeight"] as? NSNumber
        self.autoDeletion = dictionary["autoDeletion"] as? NSNumber
        self.messageId = dictionary["messageId"] as? String
    }
}

1 个答案:

答案 0 :(得分:0)

如果启用了autoDeletion,那么如何使用performSelector:withObject:AfterDelay来调用将此消息对象作为参数的函数,并将其从消息数组( final ConnectionFactory factory = new JmsConnectionFactory(uri); final Connection connection = factory.createConnection(); connection.start(); final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); )中删除并重新加载表视图。这样你就不必处理定时器或使它们失效。

记得在收到邮件对象时调用performSelector,这样邮件会在收到邮件后的适当时间间隔内被删除