之前实现的代码是:
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传递额外的参数