最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift给NSTimer中通过userInfo给scheduledtimerwithtimeinterval传递额外的参数

Swift crifan 3284浏览 0评论

之前实现的代码是:

    func smartSaveData(uniqueId:String, target: AnyObject, reallySaveData:Selector){

                let resetedTimer = NSTimer.scheduledTimerWithTimeInterval(ArchiveSmartSaveDelayTimeInSec, target: target, selector:reallySaveData, userInfo: nil, repeats: false)

想要传递额外参数,所以去加上了userInfo:

    func smartSaveData(uniqueId:String, target: AnyObject, reallySaveData:Selector, userInfo:AnyObject? = nil){

                let resetedTimer = NSTimer.scheduledTimerWithTimeInterval(ArchiveSmartSaveDelayTimeInSec, target: target, selector:reallySaveData, userInfo: userInfo, repeats: false)

但是还是不知道在callback中如何使用,如何获得传入的参数

所以对于:

    func saveMessageListToLocal(contactId:String, latestMessageList:[Message]) {

        SingletonCommonUtil().smartSaveData(uniqueId, target: self, reallySaveData: #selector(MessageManager.reallySaveMessageListToLocal(_:latestMessageList:)))

    }

   

    func reallySaveMessageListToLocal(contactId:String, latestMessageList:[Message]){

想要传递两个额外的参数:contactId,latestMessageList

都不知道如何传入

搜:

scheduledtimerwithtimeinterval userinfo swift

ios – Pass two arguments to NSTimer in Swift – Stack Overflow

swift NSTimer userinfo – Stack Overflow

ios – UserInfo in NSTimer not passing correct information – Swift – Stack Overflow

ios – Swift NSTimer retrieving userInfo as CGPoint – Stack Overflow

【总结】

最后代码改为:

        let extarParas:[String:AnyObject] = [

            "contactId" : contactId,

            "latestMessageList" : latestMessageList,

        ]

       

        let uniqueId = "saveContactMessageList_\(contactId)"

        SingletonCommonUtil().smartSaveData(uniqueId, target: self, reallySaveData: #selector(MessageManager.reallySaveMessageListToLocal(_:)), userInfo: extarParas)

    }

   

    //func reallySaveMessageListToLocal(contactId:String, latestMessageList:[Message]){

    func reallySaveMessageListToLocal(curTimer:NSTimer){

        let extarParas = curTimer.userInfo as! [String:AnyObject]

        let contactId = extarParas["contactId"] as! String

        let latestMessageList = extarParas["latestMessageList"] as! [Message]

即可:

转载请注明:在路上 » [已解决]swift给NSTimer中通过userInfo给scheduledtimerwithtimeinterval传递额外的参数

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
91 queries in 0.182 seconds, using 22.09MB memory